安卓:java.lang.IndexOutOfBoundsException:无效指数9,尺寸为9
我有我的下面的代码有问题:安卓:java.lang.IndexOutOfBoundsException:无效指数9,尺寸为9
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick (View v) {
int row = position +1;
int listLength = data.size();
HashMap<String,String> nextRow = data.get(position+1);
if (row < listLength) {
nextRow.put("greyedOut","false");
} else {
System.out.println("HATSIKIDEE!!");
}
notifyDataSetChanged();
System.out.println(row);
System.out.println(listLength);
}
});
这段代码放在我的Adapter
并调整ListView
,它的工作原理每一行,但选择的最后一行返回以下错误时崩溃:java.lang.IndexOutOfBoundsException: Invalid index 9, size is 9
我不明白的是,的System.out.println()的输出是根据if语句:
1 of 9
2 of 9
3 of 9
4 of 9
5 of 9
6 of 9
7 of 9
8 of 9
At 9 of 9 it crashes.
Please help me how to solve this error.
试试这个,然后:
HashMap<String,String> nextRow = null;
if (position + 1 < listLength)
{
nextRow = data.get(position+1);
}
if (nextRow != null)
{
//whatever it is you are trying to achieve by detecting the next row
}
HashMap<String,String> nextRow = data.get(position);
,而不是
HashMap<String,String> nextRow = data.get(position+1);
指数总是从0
开始不是从1
那么你会得到
0 of 9
1 of 9
2 of 9
3 of 9
4 of 9
5 of 9
6 of 9
7 of 9
8 of 9
TOTAL = 9
Java使用基于零的索引 - 意味着在位置0处会有东西。这意味着在任何列表中,列表中都有0 - (n-1)个项目。
您需要更改
HashMap<String,String> nextRow = data.get(position+1);
到HashMap<String,String> nextRow = data.get(position);
让你去的最高指数为8,这是在列表中的第9个元素。 你的阵列看起来像这样: [0] - 第一元件 [1] - 第二元件 ....等。
请参阅我对上述答案的评论。 – iJar
int row = position + 1;
int listLength = data.size();
HashMap<String,String> nextRow = null;
if(row < listLength)
{
nextRow = data.get(row);
}
if(nextRow != null)
{
nextRow.put("greyedOut","false");
notifyDataSetChanged();
}
else
{
System.out.println("HATSIKIDEE!!");
}
System.out.println(row);
System.out.println(listLength);
对不起凯我只是试过你的代码,它仍然给出了相同的结果。错过我触摸最后一行的那一刻。 – iJar
嗯....我不认为这是可能的,如果你改变你的方法的全身到我的代码。 –
是“HATSIKIDEE !!”曾经印过? –
太棒了!有效!!谢谢! – iJar