Recently I'm doing an app that have a Navigation Drawer and I have some items which clicking on them should open a maps activity but when doing so my app stops and shows me the following error:
FATAL EXCEPTION: main
Process: jocadoci.soloordena, PID: 2897
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at jocadoci.soloordena.MapsItaly.geoLocate(MapsItaly.java:99)
at jocadoci.soloordena.MapsItaly.onMapReady(MapsItaly.java:73)
at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzt$zza.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:380)
at wl.a(:com.google.android.gms.DynamiteModulesB:82)
at maps.ad.t$5.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I supposed that the error is because in the maps activity I have the following class that use the ArrayList.java created by Android Studio.
private void geoLocate() throws IOException {
String location = "comida rapida y pizza";
Geocoder gc = new Geocoder(this);
List<Address> list = new ArrayList<>(gc.getFromLocationName(location, 1));
Address address = list.get(0);
String locality = address.getLocality();
Toast.makeText(this, locality, Toast.LENGTH_SHORT).show();
double lat = address.getLatitude();
double lng = address.getLongitude();
goToLocationZoom(lat, lng, 16);
}
But I'm not sure what the error is. I appreciate any help and thanks in advance
Geocoder.getFromLocationName
will return null or empty list if no matches were found or there is no backend service available (documentation).
So, to solve your problem you must check if there are available results:
private void geoLocate() throws IOException {
String location = "comida rapida y pizza";
Geocoder gc = new Geocoder(this);
List<Address> list = new ArrayList<>(gc.getFromLocationName(location, 1));
if (list != null && list.size() > 0) {
Address address = list.get(0);
String locality = address.getLocality();
Toast.makeText(this, locality, Toast.LENGTH_SHORT).show();
double lat = address.getLatitude();
double lng = address.getLongitude();
goToLocationZoom(lat, lng, 16);
} else {
Toast.makeText(this, "No results found", Toast.LENGTH_SHORT).show();
}
}