Android - 在单独 class 中使用共享首选项?

Android - Using Shared Preferences in separate class?

我想使用 android 中的共享首选项保存数据。但我希望使用单独的 class 来完成这项任务。我已经实现了 class 如下所示,

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

public class SavePref {

    private Context context;

    public SavePref(Context context){
        this.context = context;
    }

    public void saveInt(String key, int value) {

        SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt(key, value);
        editor.commit();

    }

}

但是getActivity(),

有错误
The method getActivity() is undefined for the type SavePref

如何解决?
谢谢

改变

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);

你已经有了 context 那你为什么要使用 getActivity()?

实际上getActivity()用于获取Fragment中的上下文。

getActivity()Fragment 的方法,不是您的 SavePref 的方法。在您的情况下,简单的解决方法是使用您作为成员变量保留的上下文来检索 SharedPreferences。另一种方法是避免将上下文保留为成员变量,以某种方式将共享首选项链接到 SavePref class 的实例,并使用静态方法

  public static void saveInt(Context context, String key, int value) {
        SharedPreferences sharedPref = context.getDefaultSharedPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt(key, value);
        editor.commit();
    }

并像这样解决方法:

SavePref.saveInt(getActivity(), key, value);

来自 Fragment

SavePref.saveInt(this, key, value);

来自 Activity。这样你就不需要每次调用saveInt时都实例化SavePref,并且可以避免存储对Context的引用。

我创建了一个 class 来做同样的事情。通过这种方式,您可以保存布尔值、整数、字符串数据或检查数据是否已保存在您应用程序的特定首选项组中。

因此,您需要创建一个 class "DataProccessor.java" 并将内容放在下面。此外,我将留下一些有关如何使用它的示例。

希望对您有所帮助

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

public class DataProccessor {

    private static Context context;

    public DataProccessor(Context context){
        this.context = context;
    }

    public final static String PREFS_NAME = "appname_prefs";

    public boolean sharedPreferenceExist(String key)
    {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
        if(!prefs.contains(key)){
            return true;
        }
        else {
            return false;
        }
    }

    public static void setInt( String key, int value) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME,0);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(key, value);
        editor.apply();
    }

    public static int getInt(String key) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
        return prefs.getInt(key, 0);
    }

    public static void setStr(String key, String value) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME,0);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(key, value);
        editor.apply();
    }

    public static String getStr(String key) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
        return prefs.getString(key,"DNF");
    }

    public static void setBool(String key, boolean value) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME,0);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean(key, value);
        editor.apply();
    }

    public static boolean getBool(String key) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
        return prefs.getBoolean(key,false);
    }
}

要使用它,我将向您展示一些有关如何保存字符串值的小示例,以防您希望在 Activity、片段或服务中使用它。

一个Activity

 //// To Save a value
 DataProccessor dataProccessor = new DataProccessor(this);
 dataProccessor.setStr("email","johndoe@mail.com");

 //// To Retreive a value
 dataProccessor.getStr("email");

对于片段

 //// To Save a value
 DataProccessor dataProccessor = new DataProccessor(getActivity());
 dataProccessor.setStr("email","johndoe@mail.com");

 //// To Retreive a value
 dataProccessor.getStr("email");

服务

 //// To Save a value
 DataProccessor dataProccessor = new DataProccessor(getApplicationContext());
 dataProccessor.setStr("email","johndoe@mail.com");

 //// To Retreive a value
 dataProccessor.getStr("email");

您可以在您的项目中简单地创建单独的同意 Class 并在需要保存或检索数据时以非常简单的方式调用它..

class Constant {

    companion object {

        val loginData: String = "LoginData"
        val token: String = "token"
        //create the fuction of shared prefrence
        fun setpref(context: Context): SharedPreferences {
            return context.getSharedPreferences("Table Data", Context.MODE_PRIVATE)

        }
    }
}
  class PreferenceUtil { 
    
     private var msharedPref: SharedPreferences? = null
     private var mEditor: Editor? = null
    
     companion object {
     private var sInstance: PreferenceUtils? = null
    
     fun getInstance(context: Context): PreferenceUtils {
                if (sInstance == null) {
                    sInstance = PreferenceUtils(context)
                }
                return sInstance as PreferenceUtils
            }
    }
    
     constructor()
    
        constructor(mContext: Context?) {
            msharedPref = mContext?.getSharedPreferences(APP_PREF, MODE_PRIVATE)
            mEditor = mSettings?.edit()
        }
        // get Boolean value
         fun getValue(key: String, defValue: Boolean): Boolean {
        return msharedPref!!.getBoolean(key, defValue)
    }
    // set Boolean value
    fun setValue(key: String, value: Boolean) {
        mEditor!!.putBoolean(key, value)
        mEditor!!.apply()
    }
 }


// Initialize the Pref class in your required class

class Abc : AppCompatActivity() {
   var mPreferenceUtil: PreferenceUtil = PreferenceUtils(this)

   mPreferenceUtil.setValue(ABC_POPUP, false)
}
package com.app.luandryuser.Util;

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

public class DataStorage {



    public static final int INTEGER = 1;
    public static final int FLOAT = 2;
    public static final int LONG = 3;
    public static final int STRING = 4;
    public static final int BOOLEAN = 5;
    private Context ctx;
    private SharedPreferences pref;
    private SharedPreferences.Editor writer;

    public DataStorage(Context ctx) {
        this.ctx = ctx;
        pref = ctx.getSharedPreferences("rural", Context.MODE_PRIVATE);
        writer = pref.edit();
    }

    public void write(String key, int value) {
        writer.putInt(key, value);
        writer.commit();
    }

    public void write(String key, float value) {
        writer.putFloat(key, value);
        writer.commit();
    }

    public void write(String key, String value) {
        writer.putString(key, value);
        writer.commit();
    }

    public void write(String key, boolean value) {
        writer.putBoolean(key, value);
        writer.commit();
    }

    public void write(String key, long value) {
        writer.putLong(key, value);
        writer.commit();
    }

    public Object read(String key, int DataType) {
        Object response = new Object();
        if (DataType == INTEGER)
            response = pref.getInt(key, 0);
        else if (DataType == BOOLEAN)
            response = pref.getBoolean(key, false);
        else if (DataType == LONG)
            response = pref.getLong(key, 0);
        else if (DataType == STRING)
            response = pref.getString(key, "");
        else
            response = pref.getFloat(key, 0.0f);
        return response;
    }
}

你可以使用这个 class :-

public class SharedPreferenceClass {
    private static final String USER_PREFS = "SeekingDaddie";
    private SharedPreferences appSharedPrefs;
    private SharedPreferences.Editor prefsEditor;

    // private String user_name = "user_name_prefs";
    // String user_id = "user_id_prefs";

    public SharedPreferenceClass(Context context) {
        this.appSharedPrefs = context.getSharedPreferences(USER_PREFS, Activity.MODE_PRIVATE);
        this.prefsEditor = appSharedPrefs.edit();
    }

    //get value
    public int getValue_int(String intKeyValue) {
        return appSharedPrefs.getInt(intKeyValue, 0);
    }

    public String getValue_string(String stringKeyValue) {
        return appSharedPrefs.getString(stringKeyValue, "");
    }

    public Boolean getValue_boolean(String stringKeyValue) {
        return appSharedPrefs.getBoolean(stringKeyValue, false);
    }

    //setvalue

    public void setValue_int(String intKeyValue, int _intValue) {

        prefsEditor.putInt(intKeyValue, _intValue).commit();
    }

    public void setValue_string(String stringKeyValue, String _stringValue) {

        prefsEditor.putString(stringKeyValue, _stringValue).commit();

    }

    public void setValue_boolean(String stringKeyValue, Boolean _bool) {

        prefsEditor.putBoolean(stringKeyValue, _bool).commit();

    }

    public void setValue_int(String intKeyValue) {

        prefsEditor.putInt(intKeyValue, 0).commit();
    }

    public void clearData() {
        prefsEditor.clear().commit();

    }
}