自定义对象的Andr​​oid的ArrayList - 保存到共享preferences - 序列化? [英] Android ArrayList of custom objects - Save to SharedPreferences - Serializable?

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

问题描述

我有一个对象的ArrayList。该对象包含类型位图和字符串',然后就getter和setter两者。首先是位图可序列化的?

我怎么会去这个序列,将其存储在共享preferences?我见过很多人问过类似的问题,但没有一个似乎给了一个很好的答案。我想preFER一些code的例子,如果在所有可能的。

如果位图不是序列化的话我怎么去有关存储此ArrayList <?/ P>

非常感谢。

解决方案

是的,你可以保存你的组合对象共享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&LT;列表&LT;学生&GT;&GT;(){}的getType()。
名单&LT;学生&GT;学生= 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);

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

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