iJar
iJar

Reputation: 157

Android: java.lang.IndexOutOfBoundsException: Invalid index 9, size is 9

I'm having a problem with my following code:

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

This code is placed in my Adapter and adjusts the ListView, it works for every row but crashes when selecting the last row returning the following error: java.lang.IndexOutOfBoundsException: Invalid index 9, size is 9

What I don't understand is that the output of the System.out.println() is according to if statement:

    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.

Upvotes: 0

Views: 5740

Answers (4)

Quintin B
Quintin B

Reputation: 5881

Try this then:

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
}

Upvotes: 1

Kai Huppmann
Kai Huppmann

Reputation: 10775

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

Upvotes: 1

Quintin B
Quintin B

Reputation: 5881

Java uses Zero based indexing - meaning that there will be something at position 0. This means that in any list there are 0 - (n-1) items in a list.

You need to change

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

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

so that the maximum INDEX you go to is 8, which is the 9th element in your list. Your array looks like this: [0] - 1st element [1] - 2nd element .... and so on.

Upvotes: 0

MAC
MAC

Reputation: 15847

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

instead of

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

index always starts from 0 not from 1

then you will get

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

Upvotes: 1

Related Questions