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;
}
you can't remove by index from your
sharedPreferenceShopingList
. By the time you removed the item at indexi
, the one at indexi+1
is shifted in positioni
. If you ask to remove the item at positioni+1
you can either remove the wrong item or get anArrayIndexOutBoundException
. The easy fix, could be to tag theCheckBox
with the item it represents, and call the version ofremove(T obj)
, where you will retrieve the object, throughcheckbox.getTag()
if theisChecked()
returns true.