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?

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks very helpfull but how can I do this with an array of my own object?
take a look at this answer: stackoverflow.com/a/9198626/2333395 It uses ArrayList, but shouldn't be to hard to modify for use with regular array
Put that array inside another object that implements serializable and use the above code in onPause and OnResume
how can i save model class object in arraylist and then save araylist in sharedpreferences and similarly get araylist from sharedpreferences @OrBar
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?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.