Reputation: 11
I have an Android application where I need to get address from lat/long. I have used the following code base:
Geocoder geoCoder = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> address = null;
if (geoCoder != null){
try {
address= geoCoder.getFromLocation(51.50, -0.12, 1);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (address.size()> 0){
String postCode = address.get(0).getPostalCode();
System.out.println(postCode);
}
}
I have also added the following in my manifest file
uses-permission android:name="android.permission.INTERNET"
uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
but every time I execute this block address.size()
remains "0", I have tried with different coordinates also; nothing changed at all. I'm doing all this from eclipse.
Upvotes: 1
Views: 904
Reputation: 747
Try this:
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();
}
if (addresses != null && addresses.size() > 0) {
Address address = addresses.get(0);
// Format the first line of address (if available), city, and
// country name.
final String addressText = String.format(
"%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "", address.getLocality(),
address.getCountryName());
// Update address field on UI.
mHandler.post(new Runnable() {
public void run() {
Toast.makeText(getBaseContext(),
addressText.toString(), Toast.LENGTH_SHORT)
.show();
}
});
}
return null;
}
}
Upvotes: 1