Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save custom object array to Shared Preferences

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?

like image 554
MEX Avatar asked Nov 27 '22 05:11

MEX


1 Answers

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);
like image 169
Or Bar Avatar answered Dec 09 '22 15:12

Or Bar