Geocoder.getFromLocation throws IOException on Android emulator
This is a know issue with the Emulator. It works fine on an actual device
On 2.2 API 8 you'll receive the following stacktrace
java.io.IOException: Service not Available
at android.location.Geocoder.getFromLocation(Geocoder.java:117)
See here for more info (and a possible workaround) see the following URL :
http://code.google.com/p/android/issues/detail?id=8816
If you're having issues using the GeoCoder on lower APIs you should check the stacktrace. From time to time I'm having the following :
java.io.IOException: Unable to parse response from server
at android.location.Geocoder.getFromLocation(Geocoder.java:124)
This can be anything from a server-side issue at Google, or an issue on the client (internet connection).
If the GeoCoder returns an empty list, you need to check if you have a proper GeoCoder implementation available on the device (emulator or real phone).
This can be done using the isPresent() method on the Geocoder object.
http://developer.android.com/reference/android/location/Geocoder.html
Also, when running on an emulator, make sure your AVD image is setup with the Google APIs.
You can use of Google Place API in following way
create a method that returns a JSONObject
with the response of the HTTP Call like following
public static JSONObject getLocationInfo(String address) {
StringBuilder stringBuilder = new StringBuilder();
try {
address = address.replaceAll(" ","%20");
HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObject;
}
now pass that JSONObject to getLatLong() method like following
public static GeoPoint getLatLong(JSONObject jsonObject) {
Double lon = new Double(0);
Double lat = new Double(0);
try {
lon = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");
lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
} catch (Exception e) {
e.printStackTrace();
}
return new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6));
}
this is worked and tested...on API level 8...hop this help..
I read the discussion thread mentioned by @ddewaele, someone said that reboot can solve the problem. It did. BTW, the Android version of my device is 4.1.