android - 将自定义对象数组保存到共享首选项

标签 android arrays object sharedpreferences

我可以将自己的对象数组保存到 SharedPreferences 中吗,就像下面的帖子一样?

Android ArrayList of custom objects - Save to SharedPreferences - Serializable?

但是他没有保存数组,所以是否有可能像链接后那样将自定义对象数组保存到 SharedPreferences?

最佳答案

您可以使用 gson 序列化类对象并将它们存储到 SharedPreferences 中。你可以从这里下载这个 jar https://code.google.com/p/google-gson/downloads/list

SharedPreferences  mPrefs = getPreferences(Context.MODE_PRIVATE);

保存:

Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(MyObject);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();

检索:

Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);

关于android - 将自定义对象数组保存到共享首选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20819294/

相关文章:

java - `onCreate` 方法未被调用

java - 安卓工作室 : put a GMap inside a Fragment (noob)

android - 如何在可扩展 ListView android中将 child 添加到特定的 parent

php - 从数组中提取 id 和 name

c++ - C++中的多线程,从套接字接收消息

android - 获取当前位置location android

c - 如何迭代 char 指针数组

Java - "not"扫描仪问题

Java:ObjectInputStream 返回相同的对象

object - 使用 Mockito 模拟局部范围对象的方法