The element of personal memo is strong. I'm still studying, so I'd appreciate it if you could point out any mistakes.
Create a new project in Android Studio Add the following description to the build.gradle file on the app side and sync now
dependencies {
snip
compile 'org.springframework.android:spring-android-rest-template:2.0.0.M3'
}
Because an error occurs when trying to execute restTemplate.getForObject etc. in the main thread It seems that it is necessary to execute using asynchronous processing using AsyncTask.
Sample code It is a code that executes Zip Code Search API and displays it in textViewTest.
Processing on the side where the button is pressed ↓ The linking part such as findViewById is omitted.
@Override
public void onClick(View view) {
int intId;
intId = view.getId();
switch (intId){
case R.id.buttonTest:
String zipString;
zipString = editTextZipCode.getText().toString();
Object[] getParams = new Object[1];
getParams[0] = zipString;
apiTask = new ApiTask();
apiTask.execute(getParams);
break;
}
}
class ApiTask extends AsyncTask<Object, String, String> {
@Override
protected String doInBackground(Object[] data) {
String zipCode = (String) data[0];
//Execute API using Spring
// The connection URL
String url = "http://zipcloud.ibsnet.co.jp/api/search?zipcode={zipcode}";
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();
// Add the String message converter
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
// Make the HTTP GET request, marshaling the response to a String
String result = restTemplate.getForObject(url,String.class,zipCode);
return result;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
//Post-processing after asynchronous processing is completed
@Override
protected void onPostExecute(String result) {
super.onPostExecute((String) result);
progressBar.setVisibility(View.INVISIBLE);
textViewTest.setText(result);
}
}
Recommended Posts