【发布时间】:2016-02-13 19:34:13
【问题描述】:
你好,我一直在寻找一种方法来保存和检索带有自定义对象的 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;
}
现在有一部分我只想删除arraylist中的一个对象,我该怎么做?
【问题讨论】:
-
从 SharedPreferences 中获取到 string 并用 Gson 解析到 Array,删除该项并再次保存到 SharedPreferences 中。
-
@ddog 你能告诉我一些示例代码吗
-
如何确定要从 ArrayList 中删除哪个对象?在那之后你想做点什么吗?
标签: java android arraylist sharedpreferences