SharedPreferences helper class

前端 未结 6 1058
日久生厌
日久生厌 2020-12-19 06:33

I am doing SharedPreferences helper class to make my code looks nice.

public class SharedPreferencesHelper {
    Context context;

    public SharedPreferen         


        
相关标签:
6条回答
  • 2020-12-19 07:07

    Use this :

    public class SharedPreferencesHelper {
    
    public static final String FILE_NAME = "APP_PREFERENCES";
    
      public static void put(Context context, String key, Object object) {
    
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,  Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        if (object instanceof String) {
            editor.putString(key, (String) object);
        } else if (object instanceof Integer) {
            editor.putInt(key, (Integer) object);
        } else if (object instanceof Boolean) {
            editor.putBoolean(key, (Boolean) object);
        } else if (object instanceof Float) {
            editor.putFloat(key, (Float) object);
        } else if (object instanceof Long) {
            editor.putLong(key, (Long) object);
        } else {
            editor.putString(key, object.toString());
        }
        SharedPreferencesCompat.apply(editor);
    }
    
       public static Object get(Context context, String key, Object defaultObject) {
    
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
    
        if (defaultObject instanceof String) {
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer) {
            return sp.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float) {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long) {
            return sp.getLong(key, (Long) defaultObject);
        }
    
        return null;
    }
    
    public static void remove(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(key);
        SharedPreferencesCompat.apply(editor);
    }
    
    public static void clear(Context context) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        SharedPreferencesCompat.apply(editor);
    }
    
    public static boolean contains(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        return sp.contains(key);
    }
    
    public static Map<String, ?> getAll(Context context) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        return sp.getAll();
    }
    
    
    
    private static class SharedPreferencesCompat {
        private static final Method sApplyMethod = findApplyMethod();
    
        @SuppressWarnings({"unchecked", "rawtypes"})
        private static Method findApplyMethod() {
            try {
                Class clz = SharedPreferences.Editor.class;
                return clz.getMethod("apply");
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
    
            return null;
        }
    
        public static void apply(SharedPreferences.Editor editor) {
            try {
                if (sApplyMethod != null) {
                    sApplyMethod.invoke(editor);
                    return;
                }
            } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
            editor.commit();
    
    
        }
    }
     }
    
    0 讨论(0)
  • 2020-12-19 07:07

    I would use static class if Context was a "global" context and obtaining values from the context was gruesomely long and (kinda) evil. That way, getting the value from the static class will be easier without having you to make mistake repeatingly doing the same operation all over your code space without making an error.

    And as for turning your SharedPreferencesHelper static, a good approach:

    public class SharedPreferencesHelper {
    
        private SharedPreferencesHelper(Context context){
        }
    
        private static void ensureNotNull(Context context) {
            if (context == null) {
                throw new IllegalArgumentException("Context is null.");
            }
        }
    
        public static boolean isLogged(Context context, String prefs){
            ensureNotNull(context);
            return context.getSharedPreferences(prefs,Context.MODE_PRIVATE)
                          .getBoolean("LOGGED",false);
        }
    
        public static void setLogged(Context context, String prefs){
            ensureNotNull(context);
            context.getSharedPreferences(prefs,Context.MODE_PRIVATE)
                   .edit().putBoolean("LOGGED",true).apply();
        }
    }
    
    0 讨论(0)
  • 2020-12-19 07:11

    Here this class is help you.

    import android.content.Context;
    import android.content.SharedPreferences;
    import android.content.SharedPreferences.Editor;
    import android.preference.PreferenceManager;
    //import android.preference.PreferenceManager;
    
    public class SharedPreference {
    
        private static SharedPreference   sharedPreference;
        public static final String PREFS_NAME = "AOP_PREFS";
        public static final String PREFS_KEY = "AOP_PREFS_String";
    
    
    
        public static SharedPreference getInstance()
        {
            if (sharedPreference == null)
            {
                sharedPreference = new SharedPreference();
            }
            return sharedPreference;
        }
    
        public SharedPreference() {
            super();
        }
    
        public void save(Context context, String text , String Key) {
            SharedPreferences settings;
            Editor editor;
    
            //settings = PreferenceManager.getDefaultSharedPreferences(context);
            settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); //1
            editor = settings.edit(); //2
    
            editor.putString(Key, text); //3
    
            editor.commit(); //4
        }
    
        public String getValue(Context context , String Key) {
            SharedPreferences settings;
            String text = "";
          //  settings = PreferenceManager.getDefaultSharedPreferences(context);
            settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            text = settings.getString(Key, "");
            return text;
        }
    
        public void clearSharedPreference(Context context) {
            SharedPreferences settings;
            Editor editor;
    
            //settings = PreferenceManager.getDefaultSharedPreferences(context);
            settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            editor = settings.edit();
    
            editor.clear();
            editor.commit();
        }
    
        public void removeValue(Context context , String value) {
            SharedPreferences settings;
            Editor editor;
    
            settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            editor = settings.edit();
    
            editor.remove(value);
            editor.commit();
        }
    }
    

    You can get value like this.

    String KeeLogin = SharedPreference.getInstance().getValue(getApplicationContext(), "YOUR_KEY");
    

    And Store data Like this

    SharedPreference.getInstance().save(LoginScreen.this,"VALUE","YOUR_KEY");
    

    Hope its help you :)

    0 讨论(0)
  • 2020-12-19 07:20

    I ended up with singleton pattern, keeping only one instance at the time:

    import android.content.Context;
    import android.support.annotation.NonNull;
    
    public class SharedPrefsUtil {
        private static SharedPrefsUtil instance;
        private static final String PREFS_NAME = "default_preferences";
    
        public synchronized static SharedPrefsUtil getInstance() {
            if (instance == null) {
                instance = new SharedPrefsUtil();
            }
            return instance;
        }
    
        private SharedPrefsUtil() {
        }
    
        public boolean isLoggedIn(@NonNull Context context) {
            return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
                    .getBoolean("LOGGED", false);
        }
    
        public void setLoggedIn(@NonNull Context context, boolean value) {
            context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
                    .edit().putBoolean("LOGGED", value).apply();
        }
    }
    

    Note the same singleton could be easily achieved using Dagger library.

    0 讨论(0)
  • 2020-12-19 07:31

    I wouldn't keep a reference to the context. I would rather keep the SharedPreference and its Editor as static member of your helper class. This way you won't need to instantiate SharedPreferencesHelper every time you need to read/write the SharedPreference. One step further would use the Application Context (with a your custom Application subclass) to initialize both SharedPreference and Editor, the first time you access the helper itself. That's how I would shape it

    0 讨论(0)
  • 2020-12-19 07:31

    This works for me:

    object SharedPreferenceHelper {
        private val PREF_FILE = "SharedPreference"
    
        enum class StringValues(val defValue: String) {
            Test1("");
    
            fun set(context: Context, value: String) {
                context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE).edit().putString(name, value).apply()
            }
    
            fun get(context: Context): String? = context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE).getString(name, defValue)
        }
    
        enum class IntValues(val defValue: Int) {
            Test1(0);
    
            fun set(context: Context, value: Int) {
                context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE).edit().putInt(name, value).apply()
            }
    
            fun get(context: Context): Int = context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE).getInt(name, defValue)
        }
    
        enum class LongValues(val defValue: Long) {
            Test1(0);
    
            fun set(context: Context, value: Long) {
                context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE).edit().putLong(name, value).apply()
            }
    
            fun get(context: Context): Long = context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE).getLong(name, defValue)
        }
    
        enum class FloatValues(val defValue: Float) {
            Test1(0f);
    
            fun set(context: Context, value: Float) {
                context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE).edit().putFloat(name, value).apply()
            }
    
            fun get(context: Context): Float = context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE).getFloat(name, defValue)
        }
    
        enum class BooleanValues(val defValue: Boolean) {
            Test1(true);
    
            fun set(context: Context, value: Boolean) {
                context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE).edit().putBoolean(name, value).apply()
            }
    
            fun get(context: Context): Boolean = context.getSharedPreferences(PREF_FILE, Context.MODE_PRIVATE).getBoolean(name, defValue)
        }
    }
    
    0 讨论(0)
提交回复
热议问题