我在导航视图中有一个项目列表,女巫以编程方式添加 - 我使用 sharedpreferences 保存和恢复它们,一切正常。但问题是我无法从 sharedpreferences 中删除项目。我使用标题检索项目索引单击的当前项目 - 代码工作正常 - 项目位置已正确检索但未从共享首选项中删除,没有任何作用。我可以做些什么来解决这个问题?
这是我的代码:
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);
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 NavViewArray(List<NavItem> items) {
this.navItems = new ArrayList<>(items);
}
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;
}
}