I would like to display a progress dialog when server is looking for the address on the google map, when the progress is finished, the dialog disappears. I googled it and the most of result is talking about AsyncTask, however I am still confused about the parameter of the function doInBackground() and the usage of onPreExecute() and onPostExecute(). Could someone give me some solutions about that. I really appreciate with any help, thanks.
protected void mapCurrentAddress() {
String addressString = addressText.getText().toString();
Geocoder g = new Geocoder(this);
List<Address> addresses;
try {
addresses = g.getFromLocationName(addressString, 1);
if (addresses.size() > 0) {
address = addresses.get(0);
List<Overlay> mapOverlays = mapView.getOverlays();
AddressOverlay addressOverlay = new AddressOverlay(address);
mapOverlays.add(addressOverlay);
mapView.invalidate();
final MapController mapController = mapView.getController();
mapController.animateTo(addressOverlay.getGeopoint(), new Runnable() {
public void run() {
mapController.setZoom(12);
}
});
useLocationButton.setEnabled(true);
} else {
// show the user a note that we failed to get an address
alert(this, addressString);
}
} catch (IOException e) {
// show the user a note that we failed to get an address
e.printStackTrace();
}
}
private class SearchAddress extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(AddLocationMapActivity.this);
// can use UI thread here
@Override
protected void onPreExecute() {
this.dialog.setTitle("Checking");
this.dialog.setMessage("Contacting Map Server...");
this.dialog.show();
}
// automatically done on worker thread (separate from UI thread)
@Override
protected Void doInBackground(Void... params) {
try {
mapCurrentAddress();
}
catch(Exception e) {
Log.e("DEBUGTAG", "Remote Image Exception", e);
}
return null;
}
// can use UI thread here
@Override
protected void onPostExecute(Void res) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
@Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
}
// this is the click event
mapLocationButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new SearchAddress().execute(); // crash during doing the doInBackground
//mapCurrentAddress(); // work perfectly
}
});
The application crashes after popup the progress dialog ?
There are plenty of articles on asynctasks. Some of them I am mentioning here:
http://developer.android.com/reference/android/os/AsyncTask.html
http://www.vogella.de/articles/AndroidPerformance/article.html
http://androidpartaker.wordpress.com/2010/08/01/android-async-task/
http://android10.org/index.php/articlesother/239-android-application-and-asynctask-basics
and so on. First brush up your async task concepts and start implementing them. This will surely resolve your query.