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


scenario:-

i have 2 arraylist

list contains images

postlist contains position of selected images

now when ever selecting images , press delete menu ,it should delete selected images .

when running code in debug ,its working fine , give desire output.

but when running normal mode ,its crashing , giving above exception.

if (poslist.size() > 0) {     toast.maketext(getbasecontext(), "i value" +poslist.size(),                     toast.length_short).show();     (int = 0; < 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 2  @ java.util.arraylist.throwindexoutofboundsexception(arraylist.java:251)  @ java.util.arraylist.get(arraylist.java:304) 

why behaving ,not getting clue.

thanks help.

you trying perform operation on same arraylist because of when ever remove elemnt arraylist size reduce so, you'll arrayindexoutofboundsexception. i.e when remove item appadp.list , size of appadp.list change

consider if list has 3 elemnts.

you have position in poslist 0,2

then when remove item 0 item appadp.list, size become 2 next time when try remove item @ position 2, aiobe

solution:

save items needs removed in separate list , use removeall(list) method remove items appadp.list

example:

arraylist<yourapplisttype> templist=new arraylist<yourapplisttype>(); (int = 0; < poslist.size(); i++)         templist.add(appadp.list.get(poslist.get(i))); 

and then

appadp.list.removeall(templist); 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

qt - Errors in generated MOC files for QT5 from cmake -