Encountered IndexOutOfBoundException while removing items from ListView in Android?

寵の児 提交于 2019-12-01 14:20:52
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();

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

From the look of it, you should change this

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

to

for(int i = 0; i < size; i++)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!