0

我的以下代码有问题:

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);
    }
});

此代码放置在 myAdapter并调整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.
4

4 回答 4

1
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

总计 = 9

于 2012-09-06T08:06:54.100 回答
1
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);
于 2012-09-06T08:16:20.920 回答
1

那么试试这个:

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
}
于 2012-09-06T08:17:24.850 回答
0

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

你需要改变

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


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

所以你去的最大 INDEX 是 8,这是你列表中的第 9 个元素。您的数组如下所示: [0] - 第一个元素 [1] - 第二个元素 .... 等等。

于 2012-09-06T08:09:29.443 回答