Save ArrayList to SharedPreferences

前端 未结 30 3575
野的像风
野的像风 2020-11-21 04:43

I have an ArrayList with custom objects. Each custom object contains a variety of strings and numbers. I need the array to stick around even if the user leaves

30条回答
  •  离开以前
    2020-11-21 05:21

    This method is used to store/save array list:-

     public static void saveSharedPreferencesLogList(Context context, List collageList) {
                SharedPreferences mPrefs = context.getSharedPreferences("PhotoCollage", context.MODE_PRIVATE);
                SharedPreferences.Editor prefsEditor = mPrefs.edit();
                Gson gson = new Gson();
                String json = gson.toJson(collageList);
                prefsEditor.putString("myJson", json);
                prefsEditor.commit();
            }
    

    This method is used to retrieve array list:-

    public static List loadSharedPreferencesLogList(Context context) {
            List savedCollage = new ArrayList();
            SharedPreferences mPrefs = context.getSharedPreferences("PhotoCollage", context.MODE_PRIVATE);
            Gson gson = new Gson();
            String json = mPrefs.getString("myJson", "");
            if (json.isEmpty()) {
                savedCollage = new ArrayList();
            } else {
                Type type = new TypeToken>() {
                }.getType();
                savedCollage = gson.fromJson(json, type);
            }
    
            return savedCollage;
        }
    

提交回复
热议问题