Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

android - java.lang.IndexOutOfBoundsException: Invalid index 2, size is 2

Scenario:-

I have two ArrayList

list contains images

postList contains position of selected images

now when ever i am selecting the images and press delete menu ,it should delete the selected images .

when i am running the code in debug ,its working fine and give the desire output.

but when i am running it normal mode ,its crashing and giving above exception.

if (posList.size() > 0)
{
    Toast.makeText(getBaseContext(), "i value" +posList.size(), 
                   Toast.LENGTH_SHORT).show();
    for (int i = 0; i < posList.size(); i++)
        appAdp.list.remove(appAdp.list.get(posList.get(i)));
    appAdp.notifyDataSetChanged();
    posList.clear();
    Toast.makeText(getBaseContext(), "You deleted selected items",
                   Toast.LENGTH_SHORT).show();              
}
return true;

postList values here

@Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id,
                boolean checked) {
            posList.add(position);

error showing here

appAdp.list.remove(appAdp.list.get(posList.get(i)));

logcat:-

java.lang.IndexOutOfBoundsException: Invalid index 2, size is 2

at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)

at java.util.ArrayList.get(ArrayList.java:304)

why its behaving like this ,not getting any clue.

Thanks for any help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are trying to perform operation on Same ArrayList because of that when ever you are remove elemnt from the ArrayList then its size will reduce so, You'll get ArrayIndexoutofBoundsException. i.e when you remove item from the appAdp.list , then the size of the appAdp.list will also change

consider if your list has originally 3 elemnts.

you have the position in your posList 0,2

then when you remove item from the 0 item from appAdp.list, its size will become 2 for the next time when you try to remove item at position 2, you will get AIOBE

Solution:

Save all items that needs to be removed in separate List and the use removeAll(list) method to remove items from your appAdp.list

Example:

ArrayList<yourappListtype> templist=new ArrayList<yourappListtype>();
for (int i = 0; i < posList.size(); i++)
        templist.add(appAdp.list.get(posList.get(i)));

And then

appAdp.list.removeAll(templist);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...