簡體   English   中英

為什么優先使用默認值參數

[英]why there is default value argument in preference

當我們想獲得鑰匙的價值時,我們應該做這樣的事情。

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
     */

現在我有一個問題,為什么默認值參數必須存在!

因為首選項可能尚未保存。 處理起來比編寫起來容易:

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

答案在文檔中。 如果你打電話怎么辦

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

在保存任何值之前? 它將必須返回null ,這又會產生類似NullPointerException問題。 因此,將默認值用作預防措施。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM