我有一个对象的ArrayList。该对象包含“位图”和“字符串”类型,然后分别包含这两种类型的 getter 和 setter 。首先,位图是可序列化的吗?

我将如何对其进行序列化以将其存储在SharedPreferences中?我已经看到许多人提出了类似的问题,但似乎没有一个很好的答案。如果可能的话,我希望有一些代码示例。

如果位图不可序列化,那么我该如何存储该ArrayList?

非常感谢。

最佳答案

是的,您可以将复合对象保存在共享的首选项中。比方说

 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();

..现在您可以按以下方式检索对象:
 SharedPreferences appSharedPrefs = PreferenceManager
             .getDefaultSharedPreferences(this.getApplicationContext());
 Gson gson = new Gson();
 String json = appSharedPrefs.getString("MyObject", "");
 Student mStudentObject = gson.fromJson(json, Student.class);

有关更多信息,请单击here.

如果您想找回任何类型对象的ArrayList,例如Student,然后使用:
Type type = new TypeToken<List<Student>>(){}.getType();
List<Student> students = gson.fromJson(json, type);

10-07 19:32
查看更多