SharedPreferences helper class

前端 未结 6 1059
日久生厌
日久生厌 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

    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();
        }
    }
    

提交回复
热议问题