-7

Error

java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0.

This is my code.

googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latLng) {

            Geocoder geocoder;

            geocoder = new Geocoder(MapsActivity.this, Locale.getDefault());

            try {
                addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
                String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
                String city = addresses.get(0).getLocality();
                String state = addresses.get(0).getAdminArea();
                String country = addresses.get(0).getCountryName();
                String postalCode = addresses.get(0).getPostalCode();
                String knownName = addresses.get(0).getFeatureName();

                if (city == null) {
                    Toast.makeText(MapsActivity.this, "Please select proper location", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MapsActivity.this, "" + city, Toast.LENGTH_SHORT).show();
                }

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

       }
    });
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

1 Answers1

1

GeoCoder might not return a result in all cases, since a sea or ocean might not have an address.

In this case the list of results called addresses will have 0 items, but you still try to access to first item.

You should do something like this:

addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if (addresses.size() == 0) { 
    Toast.makeText(MapsActivity.this, "Please select proper location", Toast.LENGTH_SHORT).show();
    return;
}
// ... rest of the code
Daniel Zolnai
  • 16,487
  • 7
  • 59
  • 71