mercredi 17 juin 2015

Removing all checked items in checkbox cause IndexOutOfBound exception

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;

}




Aucun commentaire:

Enregistrer un commentaire