SharedPreference是一个android的轻型存储方式。不具备Sqilit的条件查询等操作,只能保存Int,Boolean,String,Float,Long,Set<Stirng>的内容。
保存的方式是key-value的xml文件。文件存放在data/data/<包名>/Shared_prefs目录下。
实现方式:
一、根据 getSharedPreferences(String, int)
获取SharedPreferences对象
二、使用edit()方法获取SharedPreferences.Editor对象
三、通过SharedPreferences.Editor对象存储key-value数据
四、通过commit()提交数据
SharedPreference sp = getSharedPreferences("Test",Context.MODE_PRIVATE);
//获取编辑的对象
SharedPreference.Editor editor = sp.edit();
//添加数据
editor.putInt("Int_Key",0);
editor.putString("String_Key","sharedPreference存储");
editor.putBoolean("Boolean_Key",true);
//提交
editor.commit();
大家都知道getSharedPreferences(String,int)获取SharedPreferencesk可是后面的int参数是什么意思呢?
MODE_PRIVATE
//创建的SharedPreference,只能有本应用程序调用权限
- MODE_WORLD_READABLE //允许其他应用程序具有读取访问权限
- MODE_WORLD_WRITEABLE //允许其他应用程序具有写入访问权限
- MODE_MULTI_PROCESS //多进程访问权限,2.3和以前的版本是默认开启的,之后必须明确MODE_MULTI_PROCESS才能多进程访问
这里SharedPreference的存储是基本完成了。下面就是获取存入Test.xml文件的值了
int intKey = sp.getInt("Int_Key",0); //如果不存在Int_Key,则0为默认值
String stringKey = sp.getString("String_Key",null); //如果不存在String_Key,则null为默认值
Boolean booleanKey = sp.getBoolean("Boolean_Key",false); //如果不存在Boolean_Key,则false为默认值
清空Test.xml的方法是:SharedPreferences.Editor的clear()方法。
移除一个元素为:SharedPreferences.Editor的remove(String key)方法。