-->

Encountered IndexOutOfBoundException while removin

2019-02-20 19:39发布

问题:

I have one simple_list_item_multiple_choice listview in my layout and i am trying to remove all the selected items from it. I know how to delete it but i am having two major problems while deleting the items :-

  1. My program isn't deleting more than 2 items like if i selected 4 items then only 2 will be deleted and sometime its even deleting the wrong items.

  2. When i debug my code i found Array IndexOutOfBoundException in my code and as far as i know there is no exception like this in my code and its all because of deleting the wrong or less items.

here is my code:-

public void onClick(View view)
{
    SparseBooleanArray checkedPositions = new SparseBooleanArray();
    checkedPositions.clear();
    checkedPositions = lv.getCheckedItemPositions();
    int size = checkedPositions.size();
    if(size != 0)
    {
        try
        {
        for(int i = 0; i < size; i++)
        {
            if(checkedPositions.valueAt(i))
            {
                list.remove(checkedPositions.keyAt(i));
                notes.notifyDataSetChanged();
                lv.setItemChecked(i,false);
            }
        }}catch (IndexOutOfBoundsException ie)
        {}
    }
        else{}
}

I caught the exception only for debugging purpose. Thanks in advance but please help because i am stuck at this part since last two days.

回答1:

for(int i = size-1 ; i >= 0; i--) 
{
  if(checkedPositions.valueAt(i))
  {
    list.remove(checkedPositions.keyAt(i));
    //lv.setItemChecked(checkedPositions.keyAt(i),false);
  }
}
notes.notifyDataSetChanged();


回答2:

Each time you remove an item from the array at the lower lever, the total count is being reduced by 1. If you had 4 items to remove [ 0, 1, 2, 3], and you remove items starting with item 0, you have [0, 1, 2], then you remove item at 1, and you have [0, 1], if you try to remove item at index 2 which does not exist you will get an error. Try count down instead of up like this

for(int i = size; i > 0; --i)
{
  if(checkedPositions.valueAt(i))
  {
    list.remove(checkedPositions.keyAt(i));
    notes.notifyDataSetChanged();
    lv.setItemChecked(i,false);
  }
}


回答3:

From the look of it, you should change this

for(int i = 0; i <= size; i++)

to

for(int i = 0; i < size; i++)