[英]why there is default value argument in preference
when we want to get value of a key we should do something like this. 当我们想获得钥匙的价值时,我们应该做这样的事情。
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String syncConnPref = sharedPref.getString(SettingsActivity.KEY_PREF_SYNC_CONN, "defVal");
in getString document wrote. 在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
*/
now i have a question why default value argument must exist!? 现在我有一个问题,为什么默认值参数必须存在!
Because the preference may not have been saved yet. 因为首选项可能尚未保存。 It's easier to deal with this than to write: 处理起来比编写起来容易:
String value;
if (sharedPreferences.contains(PREFS_KEY)) {
value = sharedPreferences.getString(PREFS_KEY);
} else {
value = "defaultValue";
}
The answer is in the documentation. 答案在文档中。 What if you call 如果你打电话怎么办
String syncConnPref = sharedPref.getString(SettingsActivity.KEY_PREF_SYNC_CONN, "defVal");
before saving any value? 在保存任何值之前? It will have to return null
, which in turn can create problems like NullPointerException
. 它将必须返回null
,这又会产生类似NullPointerException
问题。 So, default value is used as a precaution. 因此,将默认值用作预防措施。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.