7

I want to store a custom object (let's call it MyObject) permanently so that if it is deleted from memory, I can reload it in my Activity/Fragment onResume() method when the app starts again.

How can I do that? SharedPreferences doesn't seem to have a method for storing parcelable objects.

xarlymg89
  • 2,552
  • 2
  • 27
  • 41
Michael Eilers Smith
  • 8,466
  • 20
  • 71
  • 106

2 Answers2

25

If you need to store it in SharedPreferences, you can parse your object to a json string and store the string.

private Context context;
private MyObject savedObject;
private static final String PREF_MY_OBJECT = "pref_my_object";
private SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
private Gson gson = new GsonBuilder().create();

public MyObject getMyObject() {
    if (savedObject == null) {
        String savedValue = prefs.getString(PREF_MY_OBJECT, "");
        if (savedValue.equals("")) {
            savedObject = null;
        } else {
            savedObject = gson.fromJson(savedValue, MyObject.class);
        }
    }

    return savedObject;
}

public void setMyObject(MyObject obj) {
    if (obj == null) {
        prefs.edit().putString(PREF_MY_OBJECT, "").commit();
    } else {
        prefs.edit().putString(PREF_MY_OBJECT, gson.toJson(obj)).commit();
    }
    savedObject = obj;
}

class MyObject {

}
invertigo
  • 6,336
  • 5
  • 39
  • 64
2

You can write your Bundle as a parcel to disk, then get the Parcel later and use the Parcel.readBundle() method to get your Bundle back.

hwrdprkns
  • 7,525
  • 12
  • 48
  • 69