【问题标题】:Accessing SharedPreferences without context在没有上下文的情况下访问 SharedPreferences
【发布时间】:2012-07-01 09:21:53
【问题描述】:

我已阅读有关阅读共享偏好的问题:thisthis。但是他们仍然需要 Context 来访问 SharedPreferences。我想知道如何在没有上下文的情况下访问 SharedPreferences。提前致谢

【问题讨论】:

  • 你只是不能,但只要你的应用程序正在运行,就有一个Application Context可供使用...跨度>
  • 你不能。它需要一个上下文。
  • 如果你能详细说明你为什么需要它,也许我们可以在这方面为你提供更多帮助。
  • 我很早以前就建立了自己的库,里面充满了静态方法。但是现在,我想修改那个库来保存一些用户偏好。我可以在每个静态方法调用中传递上下文,但这将迫使我在我的应用程序中重构整个类。
  • @K-ballo:如何获取 ApplicationContext

标签: android


【解决方案1】:

我通过首先检索 ApplicationContext (this) 解决我的问题,然后使用该上下文获取 SharedPreferences。感谢 K-ballo。

【讨论】:

    【解决方案2】:

    应用类:

    import android.app.Application;
    import android.content.Context;
    
    public class MyApplication extends Application {
    
        private static Context mContext;
    
        public void onCreate() {
            super.onCreate();
            mContext = getApplicationContext();
        }
    
        public static Context getAppContext() {
            return mContext;
        }
    
    }
    

    在 AndroidManifest 中声明应用程序:

    <application android:name=".MyApplication"
        ...
    />
    

    用法:

    PreferenceManager.getDefaultSharedPreferences(MyApplication.getAppContext());
    

    【讨论】:

    • 上下文是大数据,静态对象不好(内存泄漏和...)
    【解决方案3】:

    我们可以在具有 Getter 和 Setter 的辅助类中使用 SharedPreference 实例,而不涉及上下文解释 here

    MainActivity中添加

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

    然后在 PreferenceHelper 中使用 set 和 get as

    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,"");
    }
    

    【讨论】:

      猜你喜欢
      • 2011-07-31
      • 2015-01-18
      • 1970-01-01
      • 2023-03-13
      • 2018-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多