我有一个list_beneficiaries
的数组列表(类型:受益人)。在该数组列表中,我有类似Beneficiary对象的元素。像这样的东西,
list_beneficiaries.add(new Beneficiary(Integer.parseInt(obj2.getString("id")),
obj2.getString("ben_firstname"), obj2.getString("ben_lastname"));
我想在共享首选项中添加此arraylist并检索它。我怎样才能做到这一点? 我试过这个stackoverflow答案:Save ArrayList to SharedPreferences
但是,我没有得到我想要的结果。因为我有一个数组类型的对象。
答案 0 :(得分:3)
我真的很喜欢Gson。它易于使用:
Download the jar并保存到app/libs/
。
更新gradle依赖项(build.gradle):
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.code.gson:gson:2.3'
}
更新您的代码:
ArrayList<MyClass> array = new ArrayList<>();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
// Put
Gson gson = new Gson();
String json = gson.toJson(array);
editor.putString("preference_key", json);
editor.commit(); //every change in editor object is commited.
// Get
json = prefs.getString("preference_key", null);
java.lang.reflect.Type type = new TypeToken<ArrayList<MyClass>>(){}.getType();
array = gson.fromJson(json, type);
答案 1 :(得分:0)
用这个代替ArrayList<String> use List<YourObjectClass> or ArrayList<YourObjectClass>
public void saveArrayList(ArrayList<String> list, String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply(); // This line is IMPORTANT !!!
}
public ArrayList<String> getArrayList(String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
return gson.fromJson(json, type);
}