2016-01-25 27 views
0

當我們想要得到一個關鍵值時,我們應該這樣做。爲什麼有默認值參數偏好

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); 
String syncConnPref = sharedPref.getString(SettingsActivity.KEY_PREF_SYNC_CONN, "defVal"); 

在getString文件中寫道。

/** 
    * Retrieve a set of String values from the preferences. 
    * 
    * <p>Note that you <em>must not</em> modify the set instance returned 
    * by this call. The consistency of the stored data is not guaranteed 
    * if you do, nor is your ability to modify the instance at all. 
    * 
    * @param key The name of the preference to retrieve. 
    * **@param defValues Values to return if this preference does not** exist. 
    * 
    * @return Returns the preference values if they exist, or defValues. 
    * Throws ClassCastException if there is a preference with this name 
    * that is not a Set. 
    * 
    * @throws ClassCastException 
    */ 

現在我有一個問題,爲什麼默認值參數必須存在!?

回答

1

因爲首選項可能尚未保存。處理這個比寫更容易:

String value; 
if (sharedPreferences.contains(PREFS_KEY)) { 
    value = sharedPreferences.getString(PREFS_KEY); 
} else { 
    value = "defaultValue"; 
} 
+1

確實事實上,我的問題是。爲什麼android程序員在getString()中做到這一點?這個偏好是否存在與否並不是android檢查的責任。它是應用程序開發人員的責任 – rezachess

+0

最終有人需要進行檢查。幾乎沒有解決它的方法,所以API設計者認爲包含一個提供默認值的方法會很有幫助。首選項是一個很好的用例,因爲99%的時間,*有*爲默認值。 – DeeV

+0

假設您的應用有100種偏好,您認爲哪種方式更易於閱讀? – DeeV

1

答案在文檔中。如果您撥打

String syncConnPref = sharedPref.getString(SettingsActivity.KEY_PREF_SYNC_CONN, "defVal"); 

保存任何值之前?它將不得不返回null,這反過來可以產生像NullPointerException這樣的問題。所以,默認值被用作預防措施。

+1

好吧,這是真的,但我認爲誰寫的應用程序必須檢查它,這種解決方案不是好主意。 – rezachess

相關問題