更新时间:2022-12-11 10:21:19
是的,你可以保存你的组合对象共享preferences.Let说:
学生mStudentObject =新的学生();
共享preferences appShared preFS = preferenceManager
.getDefaultShared preferences(this.getApplicationContext());
编辑prefsEditor = appShared prefs.edit();
GSON GSON =新GSON();
JSON字符串= gson.toJson(mStudentObject);
prefsEditor.putString(为MyObject,JSON);
prefsEditor.commit();
,现在你可以retreive你的对象为:
共享preferences appShared preFS = preferenceManager
.getDefaultShared preferences(this.getApplicationContext());
编辑prefsEditor = appShared prefs.edit();
GSON GSON =新GSON();
JSON字符串= appShared prefs.getString(为MyObject,);
学生mStudentObject = gson.fromJson(JSON,Student.class);
有关更多信息,请点击这里
如果你想取回任何类型的任何对象,例如数组列表学生,然后使用:
输入型=新TypeToken<列表<学生>>(){}的getType()。
名单<学生>学生= gson.fromJson(JSON,类型);
I have an ArrayList of an object. The object contains the types 'Bitmap' and 'String' and then just getters and setters for both. First of all is Bitmap serializable?
How would I go about serializing this to store it in SharedPreferences? I have seen many people ask a similar question but none seem to give a good answer. I would prefer some code examples if at all possible.
If bitmap is not serializable then how do I go about storing this ArrayList?
many thanks.
Yes,you can save your composite object in shared preferences.Let say:
Student mStudentObject=new Student();
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(mStudentObject);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
and now you can retreive your object as:
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this.getApplicationContext());
Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = appSharedPrefs.getString("MyObject", "");
Student mStudentObject = gson.fromJson(json, Student.class);
for more information,click here.
If you want to get back Array List of type any any object e.g. student, then use:
Type type = new TypeToken<List<Student>>(){}.getType();
List<Student> students= gson.fromJson(json, type);