SharedPreferences助手类

时间:2016-03-10 09:21:36

标签: java android

我正在做SharedPreferences助手类,以使我的代码看起来不错。

diff --git a/app/src/main/java/com/example/android/app/MainActivity.java 
b/app/src/main/java/com/example/android/app/MainActivity.java
index 36c85c8d1f780dd7b0a6dacada717524e95bf7d4..174badb785e6f28b0d9ecd32164a7153b5f2acd5 100755
--- a/app/src/main/java/com/example/android/app/MainActivity.java
+++ b/app/src/main/java/com/example/android/app/MainActivity.java
@@ -393,7 +393,7 @@ public class MainActivity extends BaseActivity
      */
     public void showLoginFragment(boolean setAsActive) {

-        showFragment(LoginFragment_.builder().setAsActive(setAsActive)
+        showFragment(LandingFragment_.builder().setAsActive(setAsActive)
                 , true
                 , "login"
                 , true

问题是我应该将这些方法设置为静态并在每个方法中初始化SharedPreferences或更好地保留它不是静态的,并从其他类调用SharedPreferencesHelper类一次吗?感谢

6 个答案:

答案 0 :(得分:3)

我不会保留对上下文的引用。我宁愿将JsonResponseMixin及其Step 1: Go to Help -> Install New Software -> click on 'Add' Step 2: On pop-up fill these below details: Name: JavaDecompiler Location: http://jd.benow.ca/jd-eclipse/update/ Step 3: Click on checkbox - Java Decomplier Eclipse Plug-in. Step 4: Click -> Next -> Next -> Accept The Agreement -> Finish Step 5: Click on check-box -> Accept the trust certificate -> OK Step 6: Restart the eclipse. 保留为助手类的静态成员。这样,每次需要读取/写入SharedPreference时,您都不需要实例化Editor。更进一步的是使用Application SharedPreferencesHelper(带有您的自定义Application子类)来初始化SharedPreferenceContext,这是您第一次访问帮助程序本身。这就是我如何塑造它

答案 1 :(得分:2)

使用此:

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


    }
}
 }

答案 2 :(得分:1)

如果Context是一个“全局”上下文,我会使用静态类,并从上下文中获取值非常长且(有点)邪恶。这样,从静态类获取值将更容易,而不会在错误的情况下重复执行相同操作而不会出错。

至于转动SharedPreferencesHelper静态,这是一个很好的方法:

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

答案 3 :(得分:0)

我最终得到了单例模式,当时只保留了一个实例:

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

请注意,使用Dagger库可以轻松实现相同的单例。

答案 4 :(得分:0)

这对我有用:

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

答案 5 :(得分:-1)

这个课程可以帮到你。

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

你可以得到这样的价值。

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

并存储数据就像这样

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

希望它能帮到你:)。