我在Navigationview中有一个项目列表,这些项目是通过程序添加的-我使用sharedpreferences保存和还原它们,一切正常。我可以删除第一个项目-选择删除哪个项目都没关系-但是当我尝试删除第二个项目时,它将引发此异常:
java.lang.IndexOutOfBoundsException:索引:0,大小:0
如何解决此问题?
这是我的代码:
private void saveData() {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_LIST_KEY, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(navItems);
editor.putString(SHARED_PREF_LIST_KEY_ITEM, json);
editor.apply();
}
private void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_LIST_KEY, MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString(SHARED_PREF_LIST_KEY_ITEM, null);
Type type = new TypeToken<ArrayList<NavItem>>() {
}.getType();
navItems = gson.fromJson(json, type);
if (navItems == null) {
navItems = new ArrayList<>();
}
}
private void deleteData(NavItem navItem) {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_LIST_KEY, MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString(SHARED_PREF_LIST_KEY_ITEM, null);
Type type = new TypeToken<ArrayList<NavItem>>() {
}.getType();
navItems = gson.fromJson(json, type);
if (navItems != null) {
navItems.remove(navItem);
navViewArray.removeItem(navItem);
Toast.makeText(this, "List " + navItem.getName() + "
deleted ", Toast.LENGTH_SHORT).show();
saveData(); // save updated data to shared preferences
}
}
int position = navViewArray.findItemString(checkItemTitle);
Toast.makeText(this, "position " + position,
Toast.LENGTH_SHORT).show();
NavItem navItem = navItems.get(position);
deleteData(navItem);
public class NavItem {
private String name;
public NavItem(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class NavViewArray {
private List<NavItem> navItems;
public void addItem(NavItem navItem) {
navItems.add(navItem);
navViewArray.addItem(new NavItem(listName));
}
public int findItemString(String itemName) {
for (int i = 0; i < navItems.size(); i++) {
NavItem navItem = navItems.get(i);
if (itemName.equals(navItem.getName())) {
return i;
}
}
return -1;
}
public void removeItem(NavItem navItem){
navItems.remove(navItem);
}
}