2015-06-22 122 views
2

我正在編寫一個程序,需要檢查默認的首選項設置並作出相應的響應。儘管R.xml.preferences的defaultValues設置爲true,但getBoolean方法始終返回false。我已經測試了 preferences.contains(prefKey) 並且這已經返回true。getBoolean返回false

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_fullscreen); 
    PreferenceManager.setDefaultValues(this, R.xml.preferences, true); 

    populate(); 

} 

public void populate() { 
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); 

    try { 
    for (int x = 0; x < 9; x++) { 
     if (preferences.getBoolean(prefKey, false)){ 
     for (int max = 0; max < 20; max++) { 
      System.out.println("this ran"+ max + "times at" + i); 
     } 
     } else { 
     for (int max = 0; max < 20; max++) { 
      System.out.println("this Skipped"+ max + "times at" + i); 
     } 
     } 
    } 
    } catch (IOException ioe) { 

    } 
} 

回答

1

的嘗試清除您的首選項(在的onCreate),設置默認值前:

PreferenceManager.getDefaultSharedPreferences(this).edit().clear().commit(); 
PreferenceManager.setDefaultValues(this, R.xml.preferences, true); 

PreferenceManager.setDefaultValues()文檔重複:

注意:這不會將首選項重置爲默認值。 對於該功能,請使用getDefaultSharedPreferences(Context),然後清除它,然後調用此方法,並將此參數設置爲 true。

+0

這工作,任何機會,你可以解釋這背後的推理?以及將readAgain設置爲true? – shores

+0

@shores,我無法爲任何設計此類/方法的人說話,但我的猜測是它與初始化默認值(第一次)和重置默認值(隨後)有關。此外,似乎與默認值是否應覆蓋現有或簡單地「填充」空鍵有關。無論哪種方式,文檔都說這樣做,所以我們只需要遵循他們所說的話。另外,如果我的答案有效,請投票並接受爲正確的答案。 – hungryghost

1

正是由於這種

if (preferences.getBoolean(prefKey, false))//your default value here is false 

變化

if (preferences.getBoolean(prefKey, true)) 
+0

我不認爲這是OP要求的。當密鑰顯然已經存在時,它們變得虛假。他們不希望默認值爲true。 – hungryghost

+0

是的改變它爲true仍然似乎導致一個錯誤,所以我猜測這表明它沒有正確讀取preference.xml文件 – shores

0

也許你叫setDefaultValues以前設置prefKey爲false。根據PreferenceManager documentation

注意:這不會將首選項重置爲默認值。對於該功能,請使用getDefaultSharedPreferences(Context)並清除它,然後調用此方法,並將此參數設置爲true。