首页 > 解决方案 > 如果条件为真,则 if 语句中的函数不执行,应用程序已停止工作

问题描述

1)我通过点击地图从谷歌地图获取地址并将值与代码一起存储 place = PlacePicker.getPlace(parentActivity, data);

2)在我得到地址存储后place,我使用代码 String address[] = place.getAddress().toString().split(",");用逗号分隔地址。

3)在我选择使用这个位置后,应用程序停止工作并关闭,甚至没有运行该locationAlertDialog();方法。

我得到了错误,address[address.length-2]因为它没有值有时取决于用户选择没有完整地址的地方,所以我可以用 if 进行管理,否则进行检查的条件,如果值为 null 我显示允许用户的 AlertDialog 构建器手动输入。

错误:

java.lang.RuntimeException: 将结果 ResultInfo{who=null, request=65537, result=-1, data=Intent { (has extras) }} 传递到活动失败:java.lang.ArrayIndexOutOfBoundsException: length=1; 指数=-1

引起:java.lang.ArrayIndexOutOfBoundsException: length=1; 指数=-1

下面是我的代码:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode  == RESULT_OK) {
        if (requestCode== 1) {
            place = PlacePicker.getPlace(parentActivity, data);
            String address[] = place.getAddress().toString().split("\\,");
            String location ;

            if(address[address.length-2] == null || address[address.length-2].trim().isEmpty() || address[address.length-2].length() < 0 ){
                locationAlertDialog();  **<---The function is not execute and the application stopped working**

            }
            else{
                locationAlertDialog();
                location = place.getName() + "," + address[address.length-2] + "," + address[address.length-1];
                locationET.setText(location);
            }

        }else if (requestCode == Config.PICK_FILE_REQUEST) {
            if (data == null) {
                //no data present
                return;
            }
        }
    }
}

标签: javaandroidarrays

解决方案


String address[] = place.getAddress().toString().split("\\,");

这意味着您正在尝试拆分您的地址,\\,但如果您的地址不包含\\,或只有一个\\,匹配项怎么办。在这些情况下,您address[]将只有 0 或 1 个元素。

之后

if(address[address.length-2] == null || address[address.length-2].trim().isEmpty() || address[address.length-2].length() < 0 ){

在这一行中,您试图访问address[address.length-2]不存在的元素。

ArrayIndexOutOfBoundsException错误意味着您正在尝试访问数组中不存在的元素。例如,您有 5 个元素并试图获取第 6 个元素。


推荐阅读