How to permanently store parcelable custom object? [duplicate]

↘锁芯ラ 提交于 2019-12-19 06:18:59

问题


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.



来源:https://stackoverflow.com/questions/14839400/how-to-permanently-store-parcelable-custom-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!