Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to permanently store parcelable custom object? [duplicate]

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.

like image 955
Michael Eilers Smith Avatar asked Feb 12 '13 18:02

Michael Eilers Smith


2 Answers

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 {

}
like image 77
invertigo Avatar answered Nov 04 '22 10:11

invertigo


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.

like image 31
hwrdprkns Avatar answered Nov 04 '22 09:11

hwrdprkns