可以使用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 –