java - 如果条件为真,则 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;
}
}
}
}
解决方案
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 个元素。
推荐阅读
- c# - 如果 ClassInitialize 或 TestInitalize 失败,您如何中止运行测试用例?
- c# - 如果过滤器值为空,Entity Framework Core 返回所有数据
- python - 当我尝试对简单的化学反应进行敏感性分析时,SALib 返回错误
- c# - 如何从目录符号链接中获取文件
- python - PyInstaller 无法使用 geopandas 和 fiona 创建 exe。即使我在 .spec 文件中进行了一些更改,exe 也无法正常工作
- vue.js - Bootstrap 4 Dropdown(使用 vue.js 打开)中的复选框不可选中
- scala - 我应该添加哪个依赖项以使用 intelliJ 使用 scala-spark 在 s3 中获取 txt 文件?
- python - 无法使用python2对汉字进行unicode
- amazon-web-services - 使用 BG96 和 MQTT 协议将数据发布到 aws IoT 时连接断开
- image-processing - 从公园的航拍照片中检测垃圾?