您的位置:首页 > 移动开发 > Android开发

Android SharedPreference 数据写入不成功可能的原因

2017-07-25 13:46 260 查看
m_iSharedPre = getSharedPreferences("MyTest", MODE_PRIVATE);

如果用以下方式写入数据:

m_iSharedPre.edit().putInt("aa", 100);

m_iSharedPre.edit().commit();

那么当获取数据的时候

m_iSharedPre.getInt("aa", 0);

永远返回默认值。

这是为什么呢??来查看一下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 edit();
光看第一句就明白了,原来每次调用edit()函数都是创建一个新的Editor对象,真是坑啊!
正确的写法:
m_iSharedPre = getSharedPreferences("MyTest", MODE_PRIVATE);
m_iSharedEditor = m_iSharedPre.edit();
m_iSharedEditor .putInt("aa", 100);
m_iSharedEditor .commit();
那么当下次再开启程序的时候
m_iSharedPre.getInt("aa", 0);
返回值就是100.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android