可以使用GSON
库.. 尝试这对于保存和加载共享偏好数据:
public static void saveSharedPreferencesLogList(Set<RecordData> record) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor prefsEditor = preferences.edit();
Gson gson = new Gson();
String json = gson.toJson(record);
prefsEditor.putString("myJson", json);
prefsEditor.commit();
}
public static Set<RecordData> loadSharedPreferencesLogList() {
Set<RecordData> record = new HashSet<>(dataList);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
Gson gson = new Gson();
String json = preferences.getString("myJson", "");
if (json.isEmpty()) {
record = new Set<RecordData>();
} else {
Type type = new TypeToken<Set<RecordData>>() {
}.getType();
record = gson.fromJson(json, type);
}
return record;
}
而且把这个在您的摇篮文件:
compile 'com.google.code.gson:gson:2.6.2'
重复 - HTTP://计算器.com/questions/7057845/save-arraylist-to-sharedpreferences –
你对将它转换为一个集合是正确的,但是你以错误的方式存储它。检查上面提到的链接。 –
你也可以使用Gson库来存储和检索自定义对象 - 这里解释 - http://stackoverflow.com/a/36184406/3225001 –