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

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.
 * 
 * 

Note that you must 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 SharedPreference 数据写入不成功可能的原因)