如何使用 SharedPreferences 保存和读取 Class

How to use SharedPreferences to save and read from a Class

我想在没有 Activity 的 Class 中使用 SharedPreferences。我已经写了这段代码,但我仍然遇到错误。你能帮帮我吗?

package com.example.keypass;

import android.content.Context;
import android.content.SharedPreferences;


public class test {
    SharedPreferences sharedPreferences;


    public void loadInt(){
        sharedPreferences = this.getSharedPreferences("com.example.keypass",Context.MODE_PRIVATE);
        int usrPassword = sharedPreferences.getInt("meinInteger", 0);
    }

}

如果我在 Class 和 Activity 中使用相同的代码,它就可以工作。但是在这个 class 是行不通的。

为了能够在 class 中使用共享首选项,您必须传入上下文。您可以尝试添加一个带有上下文参数的构造函数,并在您想要的 activity 中调用此 class。

这里也许有帮助

为共享首选项制作单独的 class 文件是一个好习惯

首先,创建一个文件(class) 名称Constants.java

   public class Constants {
    
        static Constants _instance;
    
        Context context;
        SharedPreferences sharedPref;
        SharedPreferences.Editor sharedPrefEditor;
    
        public static Constants instance(Context context) {
            if (_instance == null) {
                _instance = new Constants();
                _instance.configSessionUtils(context);
            }
            return _instance;
        }

    public static Constants instance() {
        return _instance;
    }

    public void configSessionUtils(Context context) {
        this.context = context;
        sharedPref = context.getSharedPreferences("AppPreferences", Activity.MODE_PRIVATE);
        sharedPrefEditor = sharedPref.edit();
    }

    public void storeValueString(String key, String value) {
        sharedPrefEditor.putString(key, value);
        sharedPrefEditor.commit();
    }

    public String fetchValueString(String key) {
        return sharedPref.getString(key, null);
    }
}

以上代码将在您的 phone 中生成一个名为 AppPreferences

的 XML 文件

您可以在键值对中存储值的位置

现在转到要访问共享首选项的activity

Constants.instance(this.getApplicationContext());

现在,当您想要存储在共享首选项中时,请像那样使用

Constants.instance().storeValueString("companyKey", "Brainwash Inc.");

现在当您想要从共享首选项中获取数据时

String companyName = (Constants.instance().fetchValueString("companyKey"));

注意 它用于 Activity 如果你想使用内部片段使用 getactivity() 而不是 getapplicationcontext()