Reverse Geocoding returns IndexOutOfBoundsException

352 views Asked by At

I am attempting to display a simple location name in a toast. In this case, it was a popular point like "Los Angeles". I am using the following code:

Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());

    try {
        List<Address> addresses = geocoder.getFromLocation(34.0500, -118.2500, 1);

        //Line Where the error occurs
        String cityandstate = addresses.get(0).getLocality() + ", " + addresses.get(0).getAdminArea();

        Toast.makeText(getActivity(), cityandstate, Toast.LENGTH_LONG).show();

    } catch (IOException e) {
        e.printStackTrace();
    }

When I run this, I receive the error java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0. I'm not entirely sure what I'm doing wrong. All Help Is Appreciated!

UPDATE

Adding my permissions as well, for clarification:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
1

There are 1 answers

0
peshkira On

getFromLocation returns no results and you do not check for that case. Then you try to access the first result but it does not exist and you get an IndexOutOfBoundException.

You should do a null and size check before accessing the results in order to get rid of the exception:

if (addresses != null && addresses.size() > 0) {
   String cityandstate = addresses.get(0).getLocality() + ", " + addresses.get(0).getAdminArea();
   ...
} else {
  // give feedback to the user
}

Why don't you get results could be due to different reasons. Here are a few ideas.

I had similar problems with the Geocoder until I added the following permission.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

It seems that the Geocoder does not always work without this permission, because it cannot cache the results. (Android tries to optimise the calls to the server as much as possible).

Another issue could be, if you do not test on a real device, but on an emulator or some special installation of Android.

Here is a snippet of the Geocoder Docs.

The Geocoder query methods will return an empty list if there no backend service in the platform. Use the isPresent() method to determine whether a Geocoder implementation exists.