4

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?

Community
  • 1
  • 1
MEX
  • 2,664
  • 5
  • 22
  • 28

1 Answers1

32

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);
Sobhan Moradi
  • 529
  • 5
  • 17
Or Bar
  • 1,566
  • 11
  • 12
  • 1
    Thanks very helpfull but how can I do this with an array of my own object? – MEX Dec 28 '13 at 21:32
  • 1
    take a look at this answer: http://stackoverflow.com/a/9198626/2333395 It uses ArrayList, but shouldn't be to hard to modify for use with regular array – Or Bar Dec 28 '13 at 21:56
  • Put that array inside another object that implements serializable and use the above code in onPause and OnResume – Prazzy Kumar May 13 '14 at 17:44
  • how can i save model class object in arraylist and then save araylist in sharedpreferences and similarly get araylist from sharedpreferences @OrBar – user3233280 Dec 08 '14 at 15:16
  • I have a question if anyone is still watching this thread: What happens if you modify the class for the object (like adding variables, etc), will it still be able to deserialize the old object and put its data into the new one? – vedi0boy Oct 04 '15 at 13:19
  • Nvm just answered my own question by doing some tests. It turns out it will work as long as you don't change variable names. – vedi0boy Oct 04 '15 at 14:06