Reputation: 482
I am building an application that will street address from user's input using GeoCoder. Herewith piece of code I made:
Geocoder gc = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses = null;
StringBuilder sb = new StringBuilder();
String destination = edittext_destination.getText().toString();
try {
addresses = gc.getFromLocationName(destination, 10);
} catch (Exception e){
Toast.makeText(getBaseContext(), "Address not found", Toast.LENGTH_SHORT).show();
}
the code above is working but it takes some time to return the result. While waiting for the result I want to display progress spinner. I know that it should use Thread but I don't know how to start. I do hope anyone can help.
Thank you
Upvotes: 1
Views: 793
Reputation: 1944
Android Query makes all this Async stuff super easy. You can add spinners and progress bars with just a little more than an async call like this:
Setup:
ProgressDialog dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(true);
dialog.setInverseBackgroundForced(false);
dialog.setCanceledOnTouchOutside(true);
dialog.setTitle("Sending...");
String url = "http://www.google.com/uds/GnewsSearch?q=Obama&v=1.0";
You async call:
aq.progress(dialog).ajax(url, JSONObject.class, this, "jsonCb");
Check it out! Excellent response time and help from Peter Liu. This project benefits Devs!
Upvotes: 0
Reputation: 18670
You could do that with an AsyncTask
:
final String destination = edittext_destination.getText().toString();
new AsyncTask<String, Void, List<Address>>() {
private Dialog loadingDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(TestActivity.this, "Please wait", "Loading addresses...");
}
@Override
protected List<Address> doInBackground(String... params) {
String destination = params[0];
try {
Geocoder gc = new Geocoder(getBaseContext(),
Locale.getDefault());
return gc.getFromLocationName(destination, 10);
} catch (Exception e) {
return null;
}
}
@Override
protected void onPostExecute(List<Address> addresses) {
loadingDialog.dismiss();
if (addresses == null) {
Toast.makeText(getBaseContext(), "Geocoding error",
Toast.LENGTH_SHORT).show();
} else if (addresses.size() == 0) {
Toast.makeText(getBaseContext(), "Address not found",
Toast.LENGTH_SHORT).show();
} else {
// Do UI stuff with your addresses
Toast.makeText(getBaseContext(), "Addresses found: " + addresses.size(), Toast.LENGTH_SHORT).show();
}
}
}.execute(destination);
Upvotes: 1