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

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

    Try this best way :

    PreferenceConnector.java

    import android.content.Context;
    import android.content.SharedPreferences;
    import android.content.SharedPreferences.Editor;
    
    public class PreferenceConnector {
        public static final String PREF_NAME = "ENUMERATOR_PREFERENCES";
        public static final String PREF_NAME_REMEMBER = "ENUMERATOR_REMEMBER";
        public static final int MODE = Context.MODE_PRIVATE;
    
    
        public static final String name = "name";
    
    
        public static void writeBoolean(Context context, String key, boolean value) {
            getEditor(context).putBoolean(key, value).commit();
        }
    
        public static boolean readBoolean(Context context, String key,
                boolean defValue) {
            return getPreferences(context).getBoolean(key, defValue);
        }
    
        public static void writeInteger(Context context, String key, int value) {
            getEditor(context).putInt(key, value).commit();
    
        }
    
        public static int readInteger(Context context, String key, int defValue) {
            return getPreferences(context).getInt(key, defValue);
        }
    
        public static void writeString(Context context, String key, String value) {
            getEditor(context).putString(key, value).commit();
    
        }
    
        public static String readString(Context context, String key, String defValue) {
            return getPreferences(context).getString(key, defValue);
        }
    
        public static void writeLong(Context context, String key, long value) {
            getEditor(context).putLong(key, value).commit();
        }
    
        public static long readLong(Context context, String key, long defValue) {
            return getPreferences(context).getLong(key, defValue);
        }
    
        public static SharedPreferences getPreferences(Context context) {
            return context.getSharedPreferences(PREF_NAME, MODE);
        }
    
        public static Editor getEditor(Context context) {
            return getPreferences(context).edit();
        }
    
    }
    

    Write the Value :

    PreferenceConnector.writeString(this, PreferenceConnector.name,"Girish");
    

    And Get value using :

    String name= PreferenceConnector.readString(this, PreferenceConnector.name, "");
    

提交回复
热议问题