2015-12-30 66 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