Today, when implementing a save user setting to Sharedpreferences, there is a situation where data cannot be saved to sharedpreferences. After careful analysis, it is concluded that:
Android.content.SharedPreferences.Editor.putString (string key, String value)
And
Android.content.SharedPreferences.Editor.commit ()
The different editor used by these two methods is caused.
The error code is as follows:
Sharedpreferences config_sp = getsharedpreferences ("config", mode_private);
Config_sp.edit (). putstring ("Passwd_safe", encodesafepasswd);
Config_sp.edit (). commit ();
The Sharedpreferences.edit () method is described below
/**
* Create A new Editor for these preferences, through which-can make
* Modifications to the data in the preferences and atomically commit those
* Changes back to the Sharedpreferences object.
*
* <p>note that you <em>must</em> call {@link Editor#commit} to has any
* Changes perform in the Editor actually show up in the
* Sharedpreferences.
*
* @return Returns A new instance of the {@link Editor} interface, allowing
* You to modify the values of this Sharedpreferences object.
*/
As the red mark above says, this method creates a new editor object, so two times the editor object is not the same. The result is a data store failure.
Android.content.SharedPreferences.edit ()