How to permanently store parcelable custom object?

13,030

Solution 1

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 {

}

Solution 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.

Share:
13,030
Michael Eilers Smith
Author by

Michael Eilers Smith

Updated on June 15, 2022

Comments

  • Michael Eilers Smith
    Michael Eilers Smith almost 2 years

    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.

  • David Liu
    David Liu over 8 years
    How do you write the bundle as a parcel to disk?