【问题标题】:Android - How to use SharedPreferences in non-Activity class?Android - 如何在非 Activity 类中使​​用 SharedPreferences?
【发布时间】:2011-11-21 10:06:12
【问题描述】:

如何在非 Activity 类中使​​用 SharedPreferences?我尝试制作一个通用的 Preferences 实用程序类并导入 android.content.Context,但 Eclipse 仍然不允许我使用 getSharedPreferences()

【问题讨论】:

    标签: android sharedpreferences


    【解决方案1】:

    在主活动中添加:你将获得全局静态共享首选项对象

     companion object {    
        lateinit var sharedPreferences: SharedPreferences
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
     sharedPreferences = applicationContext.getSharedPreferences(
            SHARED_PREFERENCE_NAME,
            Context.MODE_PRIVATE
        )
    

    【讨论】:

      【解决方案2】:

      我找到的解决方案是:

      1-在 MainActivity 类中(即总是在获取项目中的任何上下文之前启动)为上下文创建一个静态变量:

      public static Context contextOfApplication;

      2-在该类的一个重要方法(如onCreate、构造函数等)中使用getApplicationContext方法初始化这个变量:

      public void onCreate() {
          contextOfApplication = getApplicationContext();
      }
      

      3-在同一个类中为这个变量创建一个“getter”方法(也必须是静态的):

      public static Context getContextOfApplication(){
          return contextOfApplication;
      }
      

      4-在非活动类中通过静态调用创建的方法获取上下文:

      Context applicationContext = MyActivityClass.getContextOfApplication();

      5-使用PreferenceManager类获取SharedPreferences变量:

      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext);
      

      希望对你有帮助。

      【讨论】:

      • 这是一个有用的解决方法,我建议使用 contextOfApplication 作为私有字段
      • 也可以使用 applicationContext.getSharedPreferences(pref_name, MODE_PRIVATE);
      • 这是一个 hacky 解决方案和反模式,在 Activity 中公开一个公共静态 Context 变量。但是,如果您决定采用这种方式,值得注意的是,由于成员 public static Context contextOfApplication; 是公共且静态的,因此您不需要 getContextOfApplication() 方法来访问它。在第 4 步中,您只需执行 MyActivityClass.contextOfApplication 即可。
      【解决方案3】:

      Kotlin 中,有一个不错且简单的基于包装器的解决方案 - 只需将代码复制并粘贴到一个新的 AppPreferences.kt 文件中并按照 4代码中概述的 TODO 步骤

      import android.content.Context
      import android.content.Context.MODE_PRIVATE
      import android.content.SharedPreferences
      import androidx.core.content.edit
      
      object AppPreferences {
          private var sharedPreferences: SharedPreferences? = null
      
          // TODO step 1: call `AppPreferences.setup(applicationContext)` in your MainActivity's `onCreate` method
          fun setup(context: Context) {
              // TODO step 2: set your app name here
              sharedPreferences = context.getSharedPreferences("<YOUR_APP_NAME>.sharedprefs", MODE_PRIVATE)
          }
      
          // TODO step 4: replace these example attributes with your stored values
          var heightInCentimeters: Int?
              get() = Key.HEIGHT.getInt()
              set(value) = Key.HEIGHT.setInt(value)
      
          var birthdayInMilliseconds: Long?
              get() = Key.BIRTHDAY.getLong()
              set(value) = Key.BIRTHDAY.setLong(value)
      
          private enum class Key {
              HEIGHT, BIRTHDAY; // TODO step 3: replace these cases with your stored values keys
      
              fun getBoolean(): Boolean? = if (sharedPreferences!!.contains(name)) sharedPreferences!!.getBoolean(name, false) else null
              fun getFloat(): Float? = if (sharedPreferences!!.contains(name)) sharedPreferences!!.getFloat(name, 0f) else null
              fun getInt(): Int? = if (sharedPreferences!!.contains(name)) sharedPreferences!!.getInt(name, 0) else null
              fun getLong(): Long? = if (sharedPreferences!!.contains(name)) sharedPreferences!!.getLong(name, 0) else null
              fun getString(): String? = if (sharedPreferences!!.contains(name)) sharedPreferences!!.getString(name, "") else null
      
              fun setBoolean(value: Boolean?) = value?.let { sharedPreferences!!.edit { putBoolean(name, value) } } ?: remove()
              fun setFloat(value: Float?) = value?.let { sharedPreferences!!.edit { putFloat(name, value) } } ?: remove()
              fun setInt(value: Int?) = value?.let { sharedPreferences!!.edit { putInt(name, value) } } ?: remove()
              fun setLong(value: Long?) = value?.let { sharedPreferences!!.edit { putLong(name, value) } } ?: remove()
              fun setString(value: String?) = value?.let { sharedPreferences!!.edit { putString(name, value) } } ?: remove()
      
              fun remove() = sharedPreferences!!.edit { remove(name) }
          }
      }
      

      现在,您可以从应用中的任何位置获取值,如下所示:

      val heightInCentimeters: Int? = AppPreferences.heightInCentimeters
      val heightOrDefault: Int = AppPreferences.heightInCentimeters ?: 170
      

      SharedPreferences 设置值同样简单:

      AppPreferences.heightInCentimeters = 160 // sets a new value
      

      【讨论】:

        【解决方案4】:

        对于 Kotlindefault 首选项文件,您可以使用以下代码:

        val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE)
        

        【讨论】:

          【解决方案5】:

          在 Kotlin 中你可以这样做:

          val myClass = MyClass(this)
          

          现在这是您在课堂上获取上下文的方法

          class MyClass(context: Context) {
          
              val context: Context = context
          
          }
          

          现在要获得带有上下文的共享首选项,您可以这样做:

          context.getSharedPreferences(...)
          

          【讨论】:

            【解决方案6】:

            使用此代码从活动中获取context

            if (context != null) {
                SharedPreferences sharedPrefs = context.getSharedPreferences("YOUR.PACKAGE.NAME", MODE_PRIVATE);
            }
            

            【讨论】:

              【解决方案7】:

              使用静态方法使用 SharedPreference 无需上下文对象 解释here

              OnCreate

              之前的 MainActivity
              public static SharedPreferences preferences;
              

              OnCreate方法中添加

              preferences = getSharedPreferences( getPackageName() + "_preferences", MODE_PRIVATE);
              

              使用 GettersSetters

              的静态方法创建一个 PreferenceHelper
              public class PreferenceHelper {
              
              final public static String KEY_DEMO_NAME = "Demo Name";
              public static void setName(String value) {
                  MainActivity.preferences.edit().putString(KEY_DEMO_NAME, value ).commit();
              }
              public static String getName() {
                  return MainActivity.preferences.getString(KEY_DEMO_NAME,"");
              }
              

              }

              【讨论】:

                【解决方案8】:

                创建 SharedPreferences 类

                 /**
                     * @param mContext
                     * @param key
                     * @param value
                     */
                    public static void savePreferences(Context mContext, String key, String value) {
                        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putString(key, value).apply();
                    }
                
                    /**
                     * @param context
                     * @param keyValue
                     * @return
                     */
                    public static String getPreferences(Context context, String keyValue) {
                        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
                        return sharedPreferences.getString(keyValue, "");
                    }
                
                    /**
                     * @param mContext
                     */
                    public static void removeAllSharedPreferences(Context mContext) {
                        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.clear().apply();
                    }
                

                【讨论】:

                  【解决方案9】:

                  将此代码用于新类。

                  import android.content.Context;
                  import android.content.SharedPreferences;
                  
                  /**
                     * Created by Atiar Talukdar on 6/5/2017.
                  */
                  
                  public class TemporaryStorageSharedPreference {
                  protected final static int DEFAULT = 0;
                  int temp = 0;
                  
                  public int readSharedPreference(Context context, String spName,String key){
                      SharedPreferences sharedPreferences = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
                      return temp = sharedPreferences.getInt(key,DEFAULT);
                  }
                  
                  public void writeSharedPreference(Context context,String ammount,String spName,String key ){
                  
                      SharedPreferences sharedPreferences = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
                      SharedPreferences.Editor editor = sharedPreferences.edit();
                      editor.putInt(key, DEFAULT);
                      editor.commit();
                  }
                  }
                  

                  【讨论】:

                    【解决方案10】:

                    SharedPreferences 与上下文相关。 您只能通过上下文引用它。

                    您可以简单地将上下文作为参数传递给您的类。 例如在构造函数中。

                    在你的活动中做:

                    MyClass myClass = new MyClass(this);
                    

                    【讨论】:

                    • 啊哈!这正是我想要的。感谢您提供简单明了的答案。现在我可以使用context.getSharedPreferences(); 访问它。
                    • 错误是 MODE_PRIVATE 无法解析为变量
                    • 我的活动不允许在我的其他类构造函数中使用this(带有SharedPreferences 的类)。
                    • @Prasad 使用 0。是一样的。
                    【解决方案11】:

                    首先,在你的类中声明一个私有属性。就我而言,我有一个 BaseAdapter 类:

                    private final Context ctx;
                    private final Vector<Acto> actos;
                    
                    public ActoAdaptador(Context ctx, Vector<Acto> as) {
                        super();
                        this.ctx = ctx;
                        this.actos = as;
                    }
                    

                    那么,什么时候使用 SharedPreferences:

                    ctx.getSharedPreferences("com.joninazio.euskofest.UsingPreferences_preferences", Context.MODE_PRIVATE)
                    

                    这种方式至少对我有用:)

                    【讨论】:

                      【解决方案12】:

                      尝试将default preferences 与应用程序上下文一起使用。上下文类似于应用程序在 linux 或 windows 上运行的环境(例如,环境变量,如 PATH 窗口样式或控制台大小)。每个 Activity 和 Service 也有自己的上下文,例如屏幕方向、主题和标签等。但是对于您的应用程序,您不需要 Activity 的上下文,您需要应用程序的全局内容,这就是 context.getApplicationContext()很有用。这在整个应用程序中都是相同的,并且始终会为您提供相同的默认首选项。

                      【讨论】:

                      • 您能详细说明一下吗?我试过SharedPreferences prefs = getDefaultSharedPreferences(this);,但它不起作用。
                      • 使用PreferenceManager.getDefaultSharedPreferences(applicationContext); 无论您在代码中的哪个位置,都需要上下文才能使用首选项。
                      • @DanS - 当他在获取上下文时遇到问题时,您希望他从哪里获取 applicationContext?
                      • @Bamerza 正如我所说,Context 是必需的,其他答案显示如何以静态方式存储Context
                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 2021-08-12
                      • 1970-01-01
                      • 2015-01-19
                      • 2023-04-02
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      相关资源
                      最近更新 更多