SharedPreferences保存不上数据的问题解决
分类:Android, Java
阅读 (3,853)
Add comments
12月 252014
SharedPreferences貌似很简单的一个类,却也存在着陷阱,如下面,我们写了几行简单的保存配置的代码,但却隐含着bug
1 2 3 |
SharedPreferences prefs = getSharedPreferences("config", Context.MODE_PRIVATE); prefs.edit().putInt("runcount", 100); prefs.edit().apply(); |
那么为什么这段代码不能保存runcount的数据呢,因为prefs.edit()每次返回一个新的Editor对象,所以执行两次prefs.edit()其实调用的是两个Editor对象,如下adnroid源码中的解释
1 2 3 4 5 6 7 8 9 10 11 12 13 |
/** * 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 edit(); |
因此,我们应该先将prefs.edit()赋值给一个Editor对象,然后由该对象进行存值和提交操作,如下:
1 2 3 4 |
SharedPreferences prefs = getSharedPreferences("config", Context.MODE_PRIVATE); Editor editor = prefs.edit(); editor.putInt("runcount", 100); editor.apply(); |