0

我有以下代碼:移除所有簽入複選框原因IndexOutOfBound例外項目

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; 

}

+0

我認爲這個問題是getShopingItems(上下文)......這將是巨大的,如果ü可以張貼片段 –

+0

我已經編輯後與方法 –

+0

是什麼checkList'的'數據類型 –

回答

0

您無法通過指數從sharedPreferenceShopingList刪除。通過您刪除索引i項目的時候,一個索引i+1i位置移動。如果你問在位置刪除項目i+1您可以刪除了錯誤的項目或得到ArrayIndexOutBoundException。最簡單的修復,可能是來標記CheckBox與它代表的項目,並調用remove(T obj),在這裏您將檢索對象,該版本通過checkbox.getTag()如果isChecked()返回true。

相關問題