2015-12-30 53 views
1

我正在使用Android guide上的分步指南之后的偏好片段。SharedPreferences变量总是返回false

我想使用这个片段设置一些首选项,所以后面的代码我可以检查每个变量的值来执行操作。

Mi偏好片段工作正常。但是,当我尝试恢复代码中其他位置的CheckedBoxPreference的值时,它始终返回false。

这是首xml文件:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" 
    android:persistent="true" 
    > 
    <PreferenceCategory 
     android:title="NOTIFICACIONES" 
     android:key="pref_key_storage_settings"> 

    <CheckBoxPreference 
     android:key="sendMail" 
     android:defaultValue="false" 
     android:persistent="true" 
     android:summary="Send emails to contacts" 
     android:title="E-mail"/> 
</PreferenceCategory> 
</PreferenceScreen> 

这是我对我所做的使用SharedPReferences

public class Prefs{ 
    private static Prefs myPreference; 
    private SharedPreferences sharedPreferences; 
    private static final String NOMBRE_PREFERENCIAS = "MisPreferencias"; 

    public static Prefs getInstance(Context context) { 
     if (myPreference == null) { 
      myPreference = new Prefs(context); 
     } 
     return myPreference; 
    } 

    private Prefs(Context context) { 

     sharedPreferences = context.getSharedPreferences(NOMBRE_PREFERENCIAS,context.MODE_PRIVATE); 
    } 

public Boolean getBoolean(String key) 
    { 
     boolean returned = false; 

     if (sharedPreferences!= null) { 
      returned = sharedPreferences.getBoolean(key,false); 
     } 

     return returned; 
    } 
} 

类这就是我如何检查是否选择的选项,所以我可以把/或不电子邮件给客户

Prefs preferences = Prefs.getInstance(getApplicationContext()); 
     if(preferences.getBoolean("sendMail") 
     { 
      // .... send email 
     } 

就像我说的,有什么奇怪的是,这是在设置持久片段(如果我选择sendEmmail选项,即使关闭应用程序并重新打开它也会被选中。但是,当我使用我的方法检查值时,它总是返回false。

我在做什么错?

谢谢

+0

Propably你没有正确保存的值,你有没有使用'value.commit();'或' value.apply();'你的保存方法结束时的方法?我没有看到保存代码,请添加它 – piotrek1543

+0

我没有编写任何代码,因为它应该在更改checkedPreference的状态时自动更改值。我错了吗?正如我所说,似乎是存储的价值,因为我能够看到状态每次我进入我的preferenceFragment和检查状态相应地改变,即使我关闭并重新启动应用程序。但是,我无法手动检索上面的代码。这是我不明白的。 – Asaak

回答

3

由于您使用的偏好片段,您应该使用PreferenceManager.getDefaultSharedPreferences(android.content.Context)检索您的喜好。您目前正在使用指定的首选项。

developer.android.com on PreferenceFragment

显示偏好对象作为列表的层次结构。当用户与 交互时,这些首选项 将自动保存到SharedPreferences。要检索此片段中首选层次结构将使用的SharedPreferences实例,请调用 getDefaultSharedPreferences(android.content.Context),其中的上下文位于 与此片段相同的包中。

所以行

sharedPreferences = context.getSharedPreferences(NOMBRE_PREFERENCIAS,context.MODE_PRIVATE); 

应改为:

sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); 
+1

很好用,谢谢! – Asaak