Android Geocoder getFromLocationName always returns null

Geocoder doesn’t always return a value. You can try to send a request 3 times in a for loop. I should be able to return atleast once. If not then, their might be a connection issue or can be other issues like server dis not reply to your request. Try and see these threads:

Geocoder doesn’t always return a value and geocoder.getFromLocationName returns only null

Updated:

I had a while loop as well but I used to try it maximum for 10 times. Sometimes, it never returned anything even if it was connected t internet. Then, I used this much more reliable way to get the address everytime:

public JSONObject getLocationInfo() {

        HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        StringBuilder stringBuilder = new StringBuilder();

        try {
            response = client.execute(httpGet);
            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) {
            e.printStackTrace();
        }
        return jsonObject;
    }
    

I called it as follows:

JSONObject ret = getLocationInfo(); 
JSONObject location;
String location_string;
try {
    location = ret.getJSONArray("results").getJSONObject(0);
    location_string = location.getString("formatted_address");
    Log.d("test", "formattted address:" + location_string);
} catch (JSONException e1) {
    e1.printStackTrace();

}

Hope this helps. I was also tired of relying on geocoder. This worked for me.
If you replace the URL with the lat and longitude coordinates and see the returned JSON object in a web browser. You’ll see what just happened.

Leave a Comment