1
votes

I am new to Android development, following is my code about use Geocoder to get city name of current location, it returns null:

private void updateCurrentLocation(Location location) { double lat = 0.0, lng = 0.0;

    if (location != null) {
        lat = location.getLatitude();
        lng = location.getLongitude();
        Log.i("tag", "Latitute is" + lat + ", Longtitute is" + lng);
    } else {
        City_Name = "Unavailable";
    }
    List<Address> list = null;
    Geocoder geocoder = new Geocoder(this.getActivity());
    try {
        list = geocoder.getFromLocation(lat, lng, 1);
    } catch (IOException e) {
        e.printStackTrace();
    }

    //may provide multiple locations.

    if (list != null && list.size() > 0) {

            Address address = list.get(0);
            City_Name = address.getLocality();

    }
    Log.i("Try", "CityName:" + City_Name);
    //send empty message
    handler.sendEmptyMessage(1);
}

I opened GPS services, add ACCESS_FINE_LOCATION and INTERNET permission in Manifest already. Also, I searched similar questions in Stackoverflow about Geocoder returns null, but haven't found useful solutions. One of them is analyze JSON from Geocoder website, but it doesn't work either.

Can anyone help with this? Thank you! BTW, is there any better solution to receive a city name? Thank you!

1
Did your code throwed an IOException?josemgu91
If you are testing on a device API 23 or above, you need to prompt permission, otherwise it will be disabled by default. A quick workaround is to approve permission from Settings>Apps> "app name" > PermissionsMoGa
@josemgu91 No, it works well, but just no any return value.LunarS
@MoGa Let me double check it. Thank you.LunarS
Did it return a null value or just an empty list? Because if the getFromLocation method can return you an empty set if it doesn't get with your location.josemgu91

1 Answers

0
votes

If the "getFromLocation" method gives you an empty set then it's because the server that is being looked up doesn't have the address information for the coordinates you're passing it. This is also noted in the docs. So I think that you should let it go and use another service like the Google Maps geocoding service or another one like Nominatim from the OpenStreetMap project.