Save custom object array to Shared Preferences

余生颓废 提交于 2020-01-01 14:48:22

问题


Can I save my own object array to the SharedPreferences, like in the post below?

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

But there he doesn't save an array, so is there a possibility to save a custom object array to SharedPreferences like in the post of the link?


回答1:


You can use gson to serialize class objects and store them into SharedPreferences. You can downlaod this jar from here https://code.google.com/p/google-gson/downloads/list

SharedPreferences  mPrefs = getPreferences(Context.MODE_PRIVATE);

To Save:

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

To Retreive:

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


来源:https://stackoverflow.com/questions/20819294/save-custom-object-array-to-shared-preferences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!