单击导航抽屉中的项目后尝试启动地图活动

问题描述 投票:0回答:1

最近我正在制作一个具有导航抽屉的应用程序,并且我有一些项目,单击它们应该打开地图活动,但这样做时我的应用程序停止并显示以下错误:

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)  

我认为该错误是因为在地图活动中我有以下使用 Android Studio 创建的 ArrayList.java 的类。

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);

}

但我不确定错误是什么。我感谢任何帮助并提前致谢

java android google-maps arraylist
1个回答
0
投票
如果未找到匹配项或没有可用的后端服务,

Geocoder.getFromLocationName
将返回 null 或空列表(文档)。

因此,要解决您的问题,您必须检查是否有可用的结果:

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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.