自定义对象的Android ArrayList-保存到SharedPreferences

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

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

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

非常感谢。


江户川乱折腾
浏览 781回答 4
4回答

拉莫斯之舞

是的,您可以将复合对象保存在共享的首选项中。比方说&nbsp;Student mStudentObject = new Student();&nbsp;SharedPreferences appSharedPrefs = PreferenceManager&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.getDefaultSharedPreferences(this.getApplicationContext());&nbsp;Editor prefsEditor = appSharedPrefs.edit();&nbsp;Gson gson = new Gson();&nbsp;String json = gson.toJson(mStudentObject);&nbsp;prefsEditor.putString("MyObject", json);&nbsp;prefsEditor.commit();&nbsp;..现在您可以按以下方式检索对象:&nbsp;SharedPreferences appSharedPrefs = PreferenceManager&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.getDefaultSharedPreferences(this.getApplicationContext());&nbsp;Gson gson = new Gson();&nbsp;String json = appSharedPrefs.getString("MyObject", "");&nbsp;Student mStudentObject = gson.fromJson(json, Student.class);有关更多信息,请单击此处。如果您想获取ArrayList任何类型的对象(例如)Student,请使用:Type type = new TypeToken<List<Student>>(){}.getType();List<Student> students = gson.fromJson(json, type);

一只名叫tom的猫

对我来说,它像这样工作:将值放在SharedPreferances中:String key = "Key";ArrayList<ModelClass> ModelArrayList=new ArrayList();SharedPreferences shref;SharedPreferences.Editor editor;shref = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);Gson gson = new Gson();String json = gson.toJson(ModelArrayList);editor = shref.edit();editor.remove(key).commit();editor.putString(key, json);editor.commit();要从SharedPreferances获取值:Gson gson = new Gson();String response=shref.getString(key , "");ArrayList<ModelClass> lstArrayList = gson.fromJson(response,&nbsp;&nbsp; &nbsp; new TypeToken<List<ModelClass>>(){}.getType());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Android