android开发中,可能需要持久化少量的数据,譬如说一些用户设置的数据,用数据库就有点杀鸡用牛刀了,这时候可以尝试使用SharedPreferences。SharedPreferences是一种轻量级的存储数据的方式,使用xml文件来进行键值对方式的存储,而且使用起来非常轻量和快捷。
得到SharedPreferences:
<span style="font-family:SimSun;font-size:18px;">SharedPreferences sharedPreferences = getSharedPreferences(
"usable_sharedPreferences", Context.MODE_PRIVATE);</span>
SharedPreferences使用一个内部类SharedPreferences.Editor来对数据进行编辑
得到edit:
<span style="font-family:SimSun;font-size:18px;">SharedPreferences.Editor editor = sharedPreferences.edit();</span>
提交数据:
<span style="font-family:SimSun;font-size:18px;">editor.putString(key, value);
editor.commit();</span>
查询数据:
<span style="font-family:SimSun;font-size:18px;">String value = sharedPreferences.getString(key, "没有找到键:" + key
+ " 对应的值,请检查输入的键!");</span>
清空数据:
<span style="font-family:SimSun;font-size:18px;">editor.clear().commit();</span>