自定义对象的 Android ArrayList - 保存到 SharedPreferences - 可序列化? [英] Android ArrayList of custom objects - Save to SharedPreferences - Serializable?

查看:35
本文介绍了自定义对象的 Android ArrayList - 保存到 SharedPreferences - 可序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象的 ArrayList.该对象包含类型 'Bitmap' 和 'String' 以及两者的 getter 和 setter.首先是位图可序列化吗?

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?

我将如何序列化它以将其存储在 SharedPreferences 中?我看到很多人问过类似的问题,但似乎没有一个给出好的答案.如果可能的话,我更喜欢一些代码示例.

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.

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

If bitmap is not serializable then how do I go about storing this ArrayList?

推荐答案

是的,您可以将复合对象保存在共享首选项中.让我们说..

Yes, you can save your composite object in shared preferences. Let's 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 retrieve your object as:

 SharedPreferences appSharedPrefs = PreferenceManager
             .getDefaultSharedPreferences(this.getApplicationContext());
 Gson gson = new Gson();
 String json = appSharedPrefs.getString("MyObject", "");
 Student mStudentObject = gson.fromJson(json, Student.class);

欲了解更多信息,请点击此处.

For more information, click here.

如果您想取回任何类型对象的 ArrayList,例如Student,然后使用:

If you want to get back an ArrayList of any type object e.g. Student, then use:

Type type = new TypeToken<List<Student>>(){}.getType();
List<Student> students = gson.fromJson(json, type);

这篇关于自定义对象的 Android ArrayList - 保存到 SharedPreferences - 可序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆