Android - Geocoder tasks to load android.address from String or Latitude/Longitude
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Locale;
public class AddressFromStringTask extends AsyncTask<String, Void, Address> {
private final WeakReference<AddressCallback> mWeakListener;
private Exception exception;
public AddressFromStringTask(AddressCallback listener) {
mWeakListener = new WeakReference<>(listener);
}
// Decode image_holder in background.
@Override
protected Address doInBackground(String... params) {
Geocoder coder = new Geocoder(
PickupLibraryApp.getInstance().getApplicationContext(), Locale.getDefault());
try {
ArrayList<Address> addresses = (ArrayList<Address>)
coder.getFromLocationName(params[0], 1);
if (addresses != null && addresses.size() > 0) {
return addresses.get(0);
}
exception = new IOException("No valid locations found for that address");
} catch (IOException e) {
exception = e;
}
return null;
}
@Override
protected void onPostExecute(Address address) {
AddressCallback listener = mWeakListener.get();
if (listener != null) {
if (exception == null) {
listener.onLoad(address);
} else {
listener.onError(exception);
}
}
}
}
import android.location.Geocoder;
import android.os.AsyncTask;
import com.google.android.gms.maps.model.LatLng;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Locale;
public class AddressFromLocationTask extends AsyncTask<LatLng, Void, android.location.Address> {
private final WeakReference<AddressCallback> mWeakCallback;
private Exception exception;
public AddressFromLocationTask(AddressCallback callback) {
mWeakCallback = new WeakReference<>(callback);
}
// Decode image_holder in background.
@Override
protected android.location.Address doInBackground(LatLng... params) {
Geocoder coder = new Geocoder(
PickupLibraryApp.getInstance().getApplicationContext(), Locale.getDefault());
try {
LatLng latLng = params[0];
ArrayList<android.location.Address> addresses = (ArrayList<android.location.Address>)
coder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if (addresses != null && addresses.size() > 0) {
return addresses.get(0);
}
exception = new IOException("No valid locations found for that address");
} catch (IOException e) {
exception = e;
}
return null;
}
@Override
protected void onPostExecute(android.location.Address address) {
AddressCallback callback = mWeakCallback.get();
if (callback != null) {
if (exception == null) {
callback.onLoad(address);
} else {
callback.onError(exception);
}
}
}
}
public interface AddressCallback {
void onLoad(android.location.Address address);
void onError(Exception e);
}