SharedPreferences
1、特点
轻量级,存储简单数据类型,键值对类型,基于xml文件存储,私有数据空间,单例对象,线程安全
2、示例代码
写入:
private void savenUserAndPwd(Context context,String userName,String pwd){
SharedPreferences sp =context.getSharedPreferences(SP_USER,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(USER_NAME,userName);
editor.putString(USER_PWD,pwd);
editor.putInt(USER_VERSION,AppVersion.getVersionCode(this));
editor.commit();
}
读取:
SharedPreferences sp =context.getSharedPreferences(SP_USER,Context.MODE_PRIVATE);
int version = sp.getInt(USER_VERSION,-1);
if(version!=AppVersion.getVersionCode(this)){
sp.edit().clear();
sp.edit().commit();
}else{
userName = sp.getString(USER_NAME,null);
md5Pwd = sp.getString(USER_PWD,null);
if(!TextUtils.isEmpty(userName)&&!TextUtils.isEmpty(md5Pwd)) {
edtUser.setText(userName);
edtPwd.setText(md5Pwd);
}
}
3、apply 与commit
commit
会把提交结果返回提交者,并且提交到磁盘IO操作
apply
异步操作,提交到内存
小技巧:
版本升级不会删除SharedPreferences
减少单个SharedPreferences文件大小
单进程使用Context.Mode_PRIVATE