How do you save/store objects in SharedPreferences on Android?

后端 未结 20 2622
野趣味
野趣味 2020-11-22 13:35

I need to get user objects in many places, which contain many fields. After login, I want to save/store these user objects. How can we implement this kind of scenario?

<
20条回答
  •  独厮守ぢ
    2020-11-22 14: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 putObject(String key, T value) {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString(key, gson.toJson(value));
            editor.apply();
        }
    
        public  T getObject(String key, Class clazz) {
            return gson.fromJson(getString(key, null), clazz);
        }
    }
    

    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

提交回复
热议问题