Removing all checked items in checkbox cause IndexOutOfBound exception

79 views Asked by At

I have the following code:

  for (int i = 0; i < checkList.getCount(); i++) {
                  LinearLayout itemLayout = (LinearLayout) checkList.getChildAt(i);
                  CheckBox checkBox = (CheckBox) itemLayout.findViewById(R.id.checkbox);
                  if (checkBox.isChecked()) {
                    sharedPreferenceShopingList.removeShopingItem(getActivity(), i);
                  }
                }

and in sharedPreferences:

 public void removeShopingItem(Context context, int position) {

List<PlanerItems> planer = getShopingItems(context);
planer.remove(position);
saveShopingItem(context, planer);

}

I'm trying to remove all the checked item's, however, it works if i remove them one by one, or couple of items, but if i try to remove all items i get the following exception:

java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
        at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
        at java.util.ArrayList.remove(ArrayList.java:403)
        at com.thezec.zdravahrana.Utils.SharedPreferenceShopingList.removeShopingItem(SharedPreferenceShopingList.java:69)
        at com.thezec.zdravahrana.Fragments.ShopingListFragment$9.onSelection(ShopingListFragment.java:271)

I'm stuck at this, so any help would be nice.

And here is the getShopingItem:

  public ArrayList<PlanerItems> getShopingItems(Context context) {

SharedPreferences settings;
List<PlanerItems> planer;

settings = context.getSharedPreferences(PREFS_NAME,
        Context.MODE_PRIVATE);

if (settings.contains(PLANER)) {
  String jsonFavorites = settings.getString(PLANER, null);
  Gson gson = new Gson();
  PlanerItems[] favoriteItems = gson.fromJson(jsonFavorites,
          PlanerItems[].class);

  planer = Arrays.asList(favoriteItems);
  planer = new ArrayList<PlanerItems>(planer);
}
else {
  return null;
}

return (ArrayList<PlanerItems>) planer;

}

1

There are 1 answers

0
Blackbelt On

you can't remove by index from your sharedPreferenceShopingList. By the time you removed the item at index i, the one at index i+1 is shifted in position i. If you ask to remove the item at position i+1 you can either remove the wrong item or get an ArrayIndexOutBoundException. The easy fix, could be to tag the CheckBox with the item it represents, and call the version of remove(T obj), where you will retrieve the object, through checkbox.getTag() if the isChecked() returns true.