简体   繁体   中英

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.

  /**
     * 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 . So, default value is used as a precaution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM