【问题标题】:Removing all checked items in checkbox cause IndexOutOfBound exception删除复选框中的所有选中项目会导致 IndexOutOfBound 异常
【发布时间】:2015-06-17 17:04:14
【问题描述】:

我有以下代码:

  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;

}

【问题讨论】:

  • 我认为问题出在 getShopingItems(context).... 如果你能发布那个 sn-p 那就太好了
  • 我已经用方法编辑了帖子
  • checkList的数据类型是什么
  • checkList 是 ListView

标签: android checkbox sharedpreferences indexoutofboundsexception


【解决方案1】:

您不能按索引从您的sharedPreferenceShopingList 中删除。当您删除索引i 处的项目时,索引i+1 处的项目将移动到i 的位置。如果您要求删除位置i+1 的项目,您可以删除错误的项目或获取ArrayIndexOutBoundException。简单的解决方法是用它所代表的项目标记CheckBox,并调用remove(T obj) 的版本,如果isChecked() 返回true,您将通过checkbox.getTag() 检索对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多