android.content.SharedPreferences.edit()

时间:2021-08-29 08:25:35

今天在实现一个保存用户设置到SharedPreferences时,出现了一个不能将数据保存到SharedPreferences中的情况。经过仔细的分析得出:

android.content.SharedPreferences.Editor.putString(String key, String value)

android.content.SharedPreferences.Editor.commit()

这两个方法所用的editor不同所致。

错误代码如下:

SharedPreferences config_sp = getSharedPreferences("config", MODE_PRIVATE);

config_sp.edit().putString("passwd_safe", enCodeSafePasswd);
config_sp.edit().commit();

SharedPreferences.edit()方法的说明如下

/**
     * Create a new Editor for these preferences, through which you 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 have any
     * changes you 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 in this SharedPreferences object.
     */

正如上面红色的标记所说,该方法会创建一个新的Editor对象,因此两次的Editor对象是不一样的。所以就造成了数据存储失败。