Android 将arraylist另存为SharedReferences
我有一个包含许多元素的recyclerview,我想在我的应用程序关闭和重新打开时将这些元素与SharedReferences一起保存。下面是我的数组的代码Android 将arraylist另存为SharedReferences,android,android-recyclerview,sharedpreferences,Android,Android Recyclerview,Sharedpreferences,我有一个包含许多元素的recyclerview,我想在我的应用程序关闭和重新打开时将这些元素与SharedReferences一起保存。下面是我的数组的代码 public ArrayList<MyInformation> getDataSet() { ArrayList results = new ArrayList<MyInformation>(); return results; } 那么,当我关闭应用程序时,如何保存
public ArrayList<MyInformation> getDataSet() {
ArrayList results = new ArrayList<MyInformation>();
return results;
}
那么,当我关闭应用程序时,如何保存此阵列?
谢谢 您可以使用Gson将SharedReferences中的数据列表保存为字符串。 在这样做之前,当然需要添加必要的存储依赖项
dependencies {
compile 'com.google.code.gson:gson:2.3.1'
}
然后,当您要保存时,将数组转换为字符串:
ArrayList<MyInformation> yourData = new ArrayList<MyInformation>();
String dataStr = new Gson().toJson(yourData);
arraylistyourdata=newarraylist();
字符串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);
String str=”“//您需要从共享首选项检索此字符串。
Type Type=new-TypeToken(){}.getType();
ArrayList restoreData=new Gson().fromJson(str,type);
您可以使用Gson将SharedReferences中的数据列表保存为字符串。 在这样做之前,当然需要添加必要的存储依赖项
dependencies {
compile 'com.google.code.gson:gson:2.3.1'
}
然后,当您要保存时,将数组转换为字符串:
ArrayList<MyInformation> yourData = new ArrayList<MyInformation>();
String dataStr = new Gson().toJson(yourData);
arraylistyourdata=newarraylist();
字符串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);
String str=”“//您需要从共享首选项检索此字符串。
Type Type=new-TypeToken(){}.getType();
ArrayList restoreData=new Gson().fromJson(str,type);
好了你在问什么问题?还要确保你的英语是正确的,这真的很难做到read@MathieuBrouwers如何在我的RecyclerViewOrry中保存元素。我在发帖的时候很匆忙。只要问我,我会很高兴地把它弄清楚的你是怎么做到的?你成功了?如果是,请将解决方案作为答案发布。谢谢你问什么问题?还要确保你的英语是正确的,这真的很难做到read@MathieuBrouwers如何在我的RecyclerViewOrry中保存元素。我在发帖的时候很匆忙。只要问我,我会很高兴地把它弄清楚的你是怎么做到的?你成功了?如果是,请将解决方案作为答案发布。谢谢,谢谢!我现在就试试,然后向你汇报。谢谢!我现在就试试,然后向你汇报。