为什么优先选择默认值参数

时间:2016-01-25 20:55:54

标签: android

当我们想获得一个键的值时,我们应该做这样的事情。

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

现在我有一个问题,为什么默认值参数必须存在!?

2 个答案:

答案 0 :(得分:1)

因为偏好可能尚未保存。处理这个比处理更容易:

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

答案 1 :(得分:1)

答案在文档中。怎么打电话

String syncConnPref = sharedPref.getString(SettingsActivity.KEY_PREF_SYNC_CONN, "defVal");
保存任何值之前

?它必须返回null,这反过来可能会产生NullPointerException等问题。因此,默认值用作预防措施。