我在Navigationview中有一个项目列表,这些列表以编程方式添加-我使用sharedpreferences保存和还原它们,一切正常。我可以删除第一个项目-选择删除哪个项目都没有关系-但是当我尝试删除第二个项目时,它会引发以下异常:java.lang.IndexOutOfBoundsException:Index:0,Size: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 NavViewArray {
private List<NavItem> navItems;
public NavViewArray() {
navItems = new ArrayList<>();
}
public void addItem(NavItem navItem) {
navItems.add(navItem);
}
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);
}
}
public class NavItem {
private String name;
public NavItem(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof NavItem)) return false;
NavItem navItem = (NavItem) o;
return getName().equals(navItem.getName());
}
@Override
public int hashCode() {
return getName().hashCode();
}
public String getName() {
return name;
}
}