gpt4 book ai didi

java - 从保存在sharedPreferences中的Arraylist中删除一个对象
转载 作者:太空宇宙 更新时间:2023-11-04 12:56:00 25 4
gpt4 key购买 nike

大家好,我一直在寻找一种方法来将带有自定义对象的Arraylist保存和检索到android Sharedpreferences中。幸运的是,我有办法使用这个 Answer 来做到这一点

public  void saveArray(ArrayList<CartItem> sKey)
{
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
SharedPreferences.Editor mEdit1 = sp.edit();

Gson gson = new Gson();
String json = gson.toJson(sKey);
mEdit1.putString("itemx", json);
mEdit1.commit();
}

public ArrayList<CartItem> readArray(){
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
String json = appSharedPrefs.getString("itemx", "");
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<CartItem>>(){}.getType();
ArrayList<CartItem> List = gson.fromJson(json, type);

return List;
}

现在我只想删除数组列表中的一个对象,我该怎么做?

最佳答案

您可以读取数组,删除元素并将其保存回来:

public void removeElement(CartItem item) {
ArrayList<CartItem> items = readArray();
items.remove(item);
saveArray(items);
}

P.s.如果您没有认真的动机同步执行此方法,我建议您在保存方法中将 commit() 替换为 apply() (保存将是异步的)。

关于java - 从保存在sharedPreferences中的Arraylist<object>中删除一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35384441/

25 4 0