Saving Serializable Objects List into sharedPreferences

前端 未结 5 1064
闹比i
闹比i 2020-12-03 05:10

Can anyone tell me how I can save a list of custom Serializable objects into SharedPreference? I am new To Android and I want to save an Arr

5条回答
  •  执笔经年
    2020-12-03 05:53

    Another good solution is to use GSON. Here's an example:

    private static final String MAP = "map";    
    private static final Type MAP_TYPE = new TypeToken>() {}.getType();
    
    private static SharedPreferences prefs = MyApplication.getContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    
    private static Map myMap;
    
    public static void saveMap (Map map) {
        SharedPreferences.Editor editor = prefs.edit();
    
        editor.putString(MAP, new Gson().toJson(map));
        editor.commit();
        myMap = map;
    }
    
    public static Map loadMap() {
        if (myMap == null) {
            myMap = new Gson().fromJson(prefs.getString(MAP, null), MAP_TYPE);
        }
        return myMap;
    }
    

    More information about gson at http://code.google.com/p/google-gson/

    Pretty simple right? ;)
    Take care

提交回复
热议问题