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

后端 未结 20 2460
野趣味
野趣味 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:12

    Step 1: Copy paste these two functions in your java file.

     public void setDefaults(String key, String value, Context context) {
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString(key, value);
            editor.commit();
        }
    
    
        public static String getDefaults(String key, Context context) {
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
            return preferences.getString(key, null);
        }
    

    Step 2: to save use:

     setDefaults("key","value",this);
    

    to retrieve use:

    String retrieve= getDefaults("key",this);
    

    You can set different shared preferences by using different key names like:

    setDefaults("key1","xyz",this);
    
    setDefaults("key2","abc",this);
    
    setDefaults("key3","pqr",this);
    
    0 讨论(0)
  • 2020-11-22 14:19
    // SharedPrefHelper is a class contains the get and save sharedPrefernce data
    public class SharedPrefHelper {
    
        // save data in sharedPrefences
        public static void setSharedOBJECT(Context context, String key, 
                                               Object value) {
    
            SharedPreferences sharedPreferences =  context.getSharedPreferences(
                    context.getPackageName(), Context.MODE_PRIVATE);
    
            SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
            Gson gson = new Gson();
            String json = gson.toJson(value);
            prefsEditor.putString(key, json);
            prefsEditor.apply();
        }
    
        // get data from sharedPrefences 
        public static Object getSharedOBJECT(Context context, String key) {
    
             SharedPreferences sharedPreferences = context.getSharedPreferences(
                               context.getPackageName(), Context.MODE_PRIVATE);
    
            Gson gson = new Gson();
            String json = sharedPreferences.getString(key, "");
            Object obj = gson.fromJson(json, Object.class);
            User objData = new Gson().fromJson(obj.toString(), User.class);
            return objData;
        }
    }
    
    // save data in your activity
    
    User user = new User("Hussein","h@h.com","3107310890983");        
    SharedPrefHelper.setSharedOBJECT(this,"your_key",user);        
    User data = (User) SharedPrefHelper.getSharedOBJECT(this,"your_key");
    
    Toast.makeText(this,data.getName()+"\n"+data.getEmail()+"\n"+data.getPhone(),Toast.LENGTH_LONG).show();
    
    // User is the class you want to save its objects
    
    public class User {
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getEmail() {
            return email;
        }
    
        public void setEmail(String email) {
            this.email = email;
        }
    
        public String getPhone() {
            return phone;
        }
    
        public void setPhone(String phone) {
            this.phone = phone;
        }
    
        private String name,email,phone;
        public User(String name,String email,String phone){
              this.name=name;
              this.email=email;
              this.phone=phone;
        }
    }
    
    // put this in gradle
    
    compile 'com.google.code.gson:gson:2.7'
    

    hope this helps you :)

    0 讨论(0)
  • 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 <T> void putObject(String key, T value) {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString(key, gson.toJson(value));
            editor.apply();
        }
    
        public <T> T getObject(String key, Class<T> clazz) {
            return gson.fromJson(getString(key, null), clazz);
        }
    }
    

    Using

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

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

    0 讨论(0)
  • 2020-11-22 14:20

    Store data in SharedPreference

    SharedPreferences mprefs = getSharedPreferences(AppConstant.PREFS_NAME, MODE_PRIVATE)
    mprefs.edit().putString(AppConstant.USER_ID, resUserID).apply();
    
    0 讨论(0)
  • 2020-11-22 14:20

    I've used jackson to store my objects (jackson).

    Added jackson library to gradle:

    api 'com.fasterxml.jackson.core:jackson-core:2.9.4'
    api 'com.fasterxml.jackson.core:jackson-annotations:2.9.4'
    api 'com.fasterxml.jackson.core:jackson-databind:2.9.4'
    

    My test class:

    public class Car {
        private String color;
        private String type;
        // standard getters setters
    }
    

    Java Object to JSON:

    ObjectMapper objectMapper = new ObjectMapper();
    String carAsString = objectMapper.writeValueAsString(car);
    

    Store it in shared preferences:

    preferences.edit().car().put(carAsString).apply();
    

    Restore it from shared preferences:

    ObjectMapper objectMapper = new ObjectMapper();
    Car car = objectMapper.readValue(preferences.car().get(), Car.class);
    
    0 讨论(0)
  • 2020-11-22 14:21

    I know this thread is bit old. But I'm going to post this anyway hoping it might help someone. We can store fields of any Object to shared preference by serializing the object to String. Here I have used GSON for storing any object to shared preference.

    Save Object to Preference :

    public static void saveObjectToSharedPreference(Context context, String preferenceFileName, String serializedObjectKey, Object object) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(preferenceFileName, 0);
        SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
        final Gson gson = new Gson();
        String serializedObject = gson.toJson(object);
        sharedPreferencesEditor.putString(serializedObjectKey, serializedObject);
        sharedPreferencesEditor.apply();
    }
    

    Retrieve Object from Preference:

    public static <GenericClass> GenericClass getSavedObjectFromPreference(Context context, String preferenceFileName, String preferenceKey, Class<GenericClass> classType) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(preferenceFileName, 0);
        if (sharedPreferences.contains(preferenceKey)) {
            final Gson gson = new Gson();
            return gson.fromJson(sharedPreferences.getString(preferenceKey, ""), classType);
        }
        return null;
    }
    

    Note :

    Remember to add compile 'com.google.code.gson:gson:2.6.2' to dependencies in your gradle.

    Example :

    //assume SampleClass exists
    SampleClass mObject = new SampleObject();
    
    //to store an object
    saveObjectToSharedPreference(context, "mPreference", "mObjectKey", mObject);
    
    //to retrive object stored in preference
    mObject = getSavedObjectFromPreference(context, "mPreference", "mObjectKey", SampleClass.class);
    

    Update:

    As @Sharp_Edge pointed out in comments, the above solution does not work with List.

    A slight modification to the signature of getSavedObjectFromPreference() - from Class<GenericClass> classType to Type classType will make this solution generalized. Modified function signature,

    public static <GenericClass> GenericClass getSavedObjectFromPreference(Context context, String preferenceFileName, String preferenceKey, Type classType)
    

    For invoking,

    getSavedObjectFromPreference(context, "mPreference", "mObjectKey", (Type) SampleClass.class)
    

    Happy Coding!

    0 讨论(0)
提交回复
热议问题