自定义 SharedPreferences 类

Pri*_*iya 5 java android sharedpreferences

我是 android 新手和学习者。我的应用程序中有主题更改选项,用户可以在其中切换主题。我使用全局变量在应用程序中保存主题编号,但当应用程序从后台清除时,它会出现损失。所以我考虑使用 SharedPreferences 来达到这个目的。我找到了一种从这里存储和检索 SharedPreference 的简单方法。

我的代码如下

public class Keystore {
    private static Keystore store;
    private SharedPreferences SP;
    private static String filename="Keys";
    public static int theme=1;

    private Keystore(Context context) {
        SP = context.getApplicationContext().getSharedPreferences(filename,0);
    }

    public static Keystore getInstance(Context context) {
        if (store == null) {
            store = new Keystore(context);
        }
        return store;
    }

    public void put(String key, String value) {
        SharedPreferences.Editor editor;
        editor = SP.edit();
        editor.putString(key, value);
        editor.apply();
    }

    public String get(String key) {
        return SP.getString(key, null);
    }

    public int getInt(String key) {
        return SP.getInt(key, 0);
    }

    public void putInt(String key, int num) {
        SharedPreferences.Editor editor;
        editor = SP.edit();

        editor.putInt(key, num);
        editor.apply();
    }

    public void clear(){
        SharedPreferences.Editor editor;
        editor = SP.edit();

        editor.clear();
        editor.apply();
    }

    public void remove(){
        SharedPreferences.Editor editor;
        editor = SP.edit();

        editor.remove(filename);
        editor.apply();
    }
}
Run Code Online (Sandbox Code Playgroud)

根据原始答案中给出的示例,我尝试在我的活动类中使用它,如下所示以获得价值

int theme= store.getInt("theme");
Log.d(getClass().getName(),"theme"+theme);
Run Code Online (Sandbox Code Playgroud)

但它返回 0 而不是 1。我还怀疑我在该类中将默认值保存为 1,例如public static int theme=1;This is the right way for saving default value in SharedPreferences?

谢谢

Int*_*iya 2

你应该使用commit ()

将您的首选项更改从该编辑器提交回它正在编辑的 SharedPreferences 对象。这会自动执行请求的修改,替换 SharedPreferences 中当前的内容。

public void putInt(String key, int num) 
    {
        SharedPreferences.Editor editor;
        editor = SP.edit();

        editor.remove("key");
        editor.putString("key", num);
        editor.commit(); // IF commit() showing warning then use apply() instead .
        editor.apply();

    }
Run Code Online (Sandbox Code Playgroud)

笔记

如果您不关心返回值并且从应用程序的主线程使用它,请考虑使用 apply() 代替。