I grab a code from the android site that do the reverse geocoding (transfering a location from numbers to a text)
It’s working fine but since my application has changed a bit I need to change this code into a normal method, right now it’s an AsyncTask. It should get a Location and return a string.
This code is a bit strange to me so I need your help guys:
private class ReverseGeocodingTask extends AsyncTask<Location, Void, Void>
{
Context mContext;
public ReverseGeocodingTask(Context context)
{
super();
mContext = context;
}
@Override
protected Void doInBackground(Location... params)
{
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
Location loc = params[0];
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
} catch (IOException e) {
e.printStackTrace();
// Update address field with the exception.
LocationService.this.address = e.toString();
}
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
// Format the first line of address (if available), city, and country name.
String addressText = String.format("%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
// Update address field on UI.
// Message.obtain(mHandler, UPDATE_ADDRESS, addressText).sendToTarget();
LocationService.this.address = addressText;
}
return null;
}
}
You start by making a method like so
change the line that grabs the first location, being the only one used, and remove it – you already have loc
Then instead of setting the address to that location service, just return it:
Splice those into the method, remove the unnecessary return statement at the end, and you’re golden.
Upon a closer look I’m also seeing an exception you’ll simply want to throw up the chain instead of handling inside this method. Let that get handled by whatever calls your method on a case-by-case basis: it’s not a problem this method can solve.