将数组列表保存为 SharedPreferences
Saving arraylist as SharedPreferences
我有一个 recyclerview,其中包含许多元素,我想在我的应用程序关闭和重新打开时使用 SharedPreferences 保存这些元素。我的数组的代码如下。
public ArrayList<MyInformation> getDataSet() {
ArrayList results = new ArrayList<MyInformation>();
return results;
}
(我在 myAdapter 中用这个向回收视图添加内容)
public void addEntity(int i, MyInformation entity) {
information.add(i, entity);
notifyItemInserted(i);
}
那么,当我关闭应用程序时,我该如何保存这个数组?
谢谢!
您可以使用 Gson 将 sharedpreferences 中的数据列表保存为字符串。
当然,在这样做之前你需要添加必要的依赖项
dependencies {
compile 'com.google.code.gson:gson:2.3.1'
}
然后当你想保存时,将你的数组转换成字符串:
ArrayList<MyInformation> yourData = new ArrayList<MyInformation>();
String dataStr = new Gson().toJson(yourData);
检索并转换回对象也很简单:
String str = "";//you need to retrieve this string from shared preferences.
Type type = new TypeToken<ArrayList<MyInformation>>() { }.getType();
ArrayList<MyInformation> restoreData = new Gson().fromJson(str, type);
给你了
我有一个 recyclerview,其中包含许多元素,我想在我的应用程序关闭和重新打开时使用 SharedPreferences 保存这些元素。我的数组的代码如下。
public ArrayList<MyInformation> getDataSet() {
ArrayList results = new ArrayList<MyInformation>();
return results;
}
(我在 myAdapter 中用这个向回收视图添加内容)
public void addEntity(int i, MyInformation entity) {
information.add(i, entity);
notifyItemInserted(i);
}
那么,当我关闭应用程序时,我该如何保存这个数组? 谢谢!
您可以使用 Gson 将 sharedpreferences 中的数据列表保存为字符串。 当然,在这样做之前你需要添加必要的依赖项
dependencies {
compile 'com.google.code.gson:gson:2.3.1'
}
然后当你想保存时,将你的数组转换成字符串:
ArrayList<MyInformation> yourData = new ArrayList<MyInformation>();
String dataStr = new Gson().toJson(yourData);
检索并转换回对象也很简单:
String str = "";//you need to retrieve this string from shared preferences.
Type type = new TypeToken<ArrayList<MyInformation>>() { }.getType();
ArrayList<MyInformation> restoreData = new Gson().fromJson(str, type);
给你了