我在Navigationview中有一个项目列表,是通过编程方式添加的-我使用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;
}
}
答案 0 :(得分:1)
要使用商品本身在List
中找到该商品,您需要实现equals和哈希码。
要使这一行代码navItems.remove(navItem);
工作,您需要NavItem类覆盖equals
和hashcode
即在这里:
public class NavItem {
private String name;
public NavItem(String name) {
this.name = name;
}
public String getName() {
return name;
}
// ADD THE BELOW
@Override
public boolean equals(NavItem other) {
return name.equals(other.name);
}
@Override
public int hashcode() {
return name.hashcode();
}
}
这是一个非常简单的等于和哈希码,您可以使用IDE 生成您的等于和哈希码,这样可以更好地考虑所有字段。
https://www.jetbrains.com/help/idea/generate-equals-and-hashcode-wizard.html
随着返回已删除的项目,您还可以验证该项目已被删除:
NavItem removed= navItems.remove(navItem);
Toast.makeText(this, "List " + removed.getName() + "deleted ",b Toast.LENGTH_SHORT).show();