从Arraylist< object>中删除一个对象.保存在sharedPreferences中 [英] Remove one object from Arraylist<object> saved in sharedPreferences
问题描述
你好,我一直在寻找一种方法来保存和检索带有自定义对象的Arraylist到Android Sharedpreferences中.幸运的是,我有一种方法可以使用答案
Hello all along i was looking for a way to save and retrieve an Arraylist with custom object into android Sharedpreferences. Lucky enough i got a way to do it using this 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;
}
现在有一部分我只想删除arraylist中的一个对象,我该怎么做?
Now here comes a part where i want to only delete one of the object in the arraylist, how can i do it?
推荐答案
您可以读取数组,删除元素并将其保存回去:
You can read the array, remove the element and save it back:
public void removeElement(CartItem item) {
ArrayList<CartItem> items = readArray();
items.remove(item);
saveArray(items);
}
P.s.如果您没有强烈的动机同步执行此方法,建议您在保存方法中将commit()
替换为apply()
(保存将是异步的).
P.s. If you haven't a serious motivation to do this method synchronously, I recommend you to replace commit()
with apply()
in your save method (the save will be async so).
这篇关于从Arraylist< object>中删除一个对象.保存在sharedPreferences中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!