删除复选框中的所有选中项会导致IndexOutOfBound异常

时间:2015-06-17 17:04:15

标签: android checkbox sharedpreferences indexoutofboundsexception

我有以下代码:

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

并在sharedPreferences中:

 public void removeShopingItem(Context context, int position) {

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

}

我试图删除所有已检查的项目,但是,如果我逐个删除它们,或者几个项目,它会起作用,但如果我尝试删除所有项目,我会得到以下异常:

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)

我坚持这一点,所以任何帮助都会很好。

这是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 个答案:

答案 0 :(得分:0)

您无法通过sharedPreferenceShopingList的索引删除。当您在索引i处移除该项时,索引i+1处的项目会移位i。如果您要求移除位置i+1上的项目,则可以删除错误的项目或获取ArrayIndexOutBoundException。简单的解决方法是,可以使用其代表的项标记CheckBox,并调用remove(T obj)的版本,如果checkbox.getTag(),则通过isChecked()调用对象。 }返回true。