Removing elements on ArrayList throw an IndexOutOfBoundsException on ArrayAdapter

自古美人都是妖i 提交于 2019-12-01 00:56:34

Override getCount(). And return the value forms.size() in it.

In my case the answer of Shubhayu was not enough. getCount and getItem must be synchronous and use the same list object. If your array adapter must use an internal List of items both need to be overriden.

public class MyArrayAdapter extends ArrayAdapter<MyItemType> {

private final List<MyItemType> items;

public MyArrayAdapter(final Context _context, final int _resource, final List<MyItemType> _items) {
  super(_context, _resource, _items);

  this.items = _items;
}

// IMPORTANT: either override both getCount and getItem or none as they have to access the same list
@Override
public int getCount() {
  return this.items.size();
};

@Override
public Site getItem(final int position) {
  return this.items.get(position);
}

...

Position is one based while array index is zero based.

So change that line:

if (!checkedItemsPosition.contains(new Integer(i)))
    copyForms.add(forms.get(i - 1));

You're using two Lists and their indexes - but these lists are in no way synced (they can change individually without checking the other).

Why not instead use a ArrayList<Form> checkForms and ArrayList<Form> uncheckedForms, then you could remove the reference to the form from uncheckedForms and add it to checkedForms which would keep both List's in sync.

When you needed to get all Forms you could then simply return a union of both ArrayLists.

No one has answered why he is getting the exception yet. So I will provide my answer here even though his question is quite old.

The reason you're getting the exception is because when you're updating "forms", you create a new array object (thus a new reference) and change the reference of forms to it while ArrayAdapter maintains its own array object mObjects, to which the constructor copies the reference of the array object you provided (objects). You can see this if you look into its source code (good thing it is open source).

To truly solve the problem you should be updating the array using the inherited functions add(...), addAll(...), etc. Or just extend baseadapter and make your own implementations.

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