安卓:java.lang.IndexOutOfBoundsException:无效指数9,尺寸为9

安卓: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 
} 
+0

太棒了!有效!!谢谢! – iJar

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

+0

的nextRow使得排在它下面的视觉和活跃的就是这句话的全部意义。但是因为在最后一行下面没有下一行,我希望它停止执行该更改。这就是为什么我将它与数组大小进行比较的原因。 – iJar

+0

试试这个'int row = position;'而不是'int row = position +1;' – MAC

+0

data.get(9)每次都会导致IndexOutOfBoundsException。你会注意到data.get(8)是你数组中最后一个元素。 你有至少尝试过我们的想法(这不是通常的2人完全一样的想法,同时是完全错误的)?发生了什么? –

Java使用基于零的索引 - 意味着在位置0处会有东西。这意味着在任何列表中,列表中都有0 - (n-1)个项目。

您需要更改

HashMap<String,String> nextRow = data.get(position+1); 


HashMap<String,String> nextRow = data.get(position);

让你去的最高指数为8,这是在列表中的第9个元素。 你的阵列看起来像这样: [0] - 第一元件 [1] - 第二元件 ....等。

+0

请参阅我对上述答案的评论。 – 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); 
+0

对不起凯我只是试过你的代码,它仍然给出了相同的结果。错过我触摸最后一行的那一刻。 – iJar

+0

嗯....我不认为这是可能的,如果你改变你的方法的全身到我的代码。 –

+0

是“HATSIKIDEE !!”曾经印过? –