【问题标题】:Getting preferences outside of PreferenceActivity在 PreferenceActivity 之外获取首选项
【发布时间】:2015-12-02 14:06:50
【问题描述】:

我收到了PreferenceActivity。当用户更改首选项时,我想保存一些额外的首选项,所以在 OnPreferencesChange 方法中,我得到了这样的内容:

if(p.getKey().equals("mykey")) //there is no issue with this if. it enters and get inside to the commit command
{
   getPreferences(MODE_PRIVATE).edit().putString("otherKey","value").commit();
   return true;
}

我还获得了一个服务(当然,它与 PreferenceActivity 的类不同),我想在其中读取首选项。所以我正在做这样的事情:

sp = PreferenceManager.getDefaultSharedPreferences();
String val1 = dsp.getString("myKey","default1");
String val2 = dsp.getString("otherKey","default2");

我得到了正确的“mykey”值,但总是得到“otherKey”的“default2”。这是为什么?会不会是 Service 获取了错误的 SharedPreference?

【问题讨论】:

    标签: android sharedpreferences preferenceactivity


    【解决方案1】:

    代替

    getPreferences(MODE_PRIVATE).edit().putString("otherKey","value").commit();
    

    做:

    PreferenceManager.getDefaultSharedPreferences( this ).edit().putString("otherKey","value").commit();
    

    根据文档,getPreferences() 返回一个“SharedPreferences 对象,用于访问此活动私有的首选项”。

    【讨论】:

      【解决方案2】:

      正如文档所说的getPreferences

      检索一个 SharedPreferences 对象以访问首选项 此活动专用。这只是简单地调用底层 通过传入此活动的 getSharedPreferences(String, int) 方法 类名作为首选项名称。

      getDefaultSharedPreferences:

      获取指向默认文件的 SharedPreferences 实例 由给定上下文中的首选项框架使用。

      所以这两个方法返回不同的首选项对象,这就是你得到默认值的原因。

      getPreferences(MODE_PRIVATE) 更改为PreferenceManager.getDefaultSharedPreferences()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-19
        相关资源
        最近更新 更多