Save ArrayList to SharedPreferences

前端 未结 30 3702
野的像风
野的像风 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:19

    My utils class for save list to SharedPreferences

    public class SharedPrefApi {
        private SharedPreferences sharedPreferences;
        private Gson gson;
    
        public SharedPrefApi(Context context, Gson gson) {
            this.sharedPreferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            this.gson = gson;
        } 
    
        ...
    
        public  void putList(String key, List list) {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString(key, gson.toJson(list));
            editor.apply();
        }
    
        public  List getList(String key, Class clazz) {
            Type typeOfT = TypeToken.getParameterized(List.class, clazz).getType();
            return gson.fromJson(getString(key, null), typeOfT);
        }
    }
    

    Using

    // for save
    sharedPrefApi.putList(SharedPrefApi.Key.USER_LIST, userList);
    
    // for retrieve
    List userList = sharedPrefApi.getList(SharedPrefApi.Key.USER_LIST, User.class);
    

    .
    Full code of my utils // check using example in Activity code

提交回复
热议问题