【发布时间】:2016-05-20 14:24:04
【问题描述】:
我正在使用一个包含多项选择项的对话框。一旦用户点击一个项目,来自itemsList 的项目将被添加到selectedItemsList,当然当用户取消选择一个项目时,该项目将从selectedItemsList 中删除。
使用Monkey 测试我的应用程序时。我收到这些错误:
java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3
...
java.lang.IndexOutOfBoundsException: Invalid index 4, size is 3
sn-p:
List<Item> itemsList; // this list is populated before accessing
List<SelectedItem> selectedItemsList;
...
dialogBuilder.setMultiChoiceItems(playlists, null, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
selectedItemsList.add(new SelectedItem(itemsList.get(which).getId()));
} else if (selectedItemsList.get(which) != null) {
selectedItemsList.remove(which);
}
}
});
我可以通过检查which 是否小于selectedItemsList.size() 来“解决”这个问题。但据我所知,如果这返回错误;该项目不会从selectedItemsList 中删除,但复选框将被取消选中。这导致一切都会混淆
【问题讨论】:
-
我猜,Arraylist 从 0 开始,onClick 的整数值从 1 开始。如果你的 onClick 整数值大于 ArrayList 的大小,那么可能会抛出 IndexOutOfBound 异常。尝试使用 .get(which-1)/.remove(which-1)。
-
@HariRam 我刚刚测试过了,onClick的整数值从0开始.. :(
-
检查 LIST 的大小。
标签: java android arraylist android-alertdialog indexoutofboundsexception