How to permanently store parcelable custom object?

2020-03-17 05:02发布

问题:

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.

回答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 {

}


回答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.