Android How to - Create Aync Task for Getting Address








Question

We would like to know how to create Aync Task for Getting Address.

Answer

import java.util.List;
import java.util.Locale;
// www  .j  a  v a  2s . c  o  m
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.util.Log;

class GetAddressTask extends AsyncTask<Location, Void, Address> {

  public interface AddressRetrievedListener {
    public void onAddressRetrieved(Address address);
  }

  private Context context;
  private AddressRetrievedListener listener;

  public GetAddressTask(Context context, AddressRetrievedListener listener) {
    this.context = context;
    this.listener = listener;
  }

  @Override
  protected Address doInBackground(Location... locations) {
    Geocoder geocoder = new Geocoder(context, Locale.getDefault());

    Location loc = locations[0];
    List<Address> addressList = null;
    try {
      addressList = geocoder.getFromLocation(loc.getLatitude(),
          loc.getLongitude(), 1);

    } catch (Exception e) {
      Log.e("GPSActivity", e.getMessage());
    }

    return (addressList != null && addressList.size() > 0) ? addressList.get(0)
        : null;
  }

  @Override
  protected void onPostExecute(Address address) {
    listener.onAddressRetrieved(address);
  }
}