SharedPreferences:分享爱好
使用步骤:
1.使用context.getSharedPreferences对象获取ShparedPreferences对象 sp,把获取到的数据存储到data.xml文件内。
SharedPreferences sp=context.getSharedPreferences("data",Context.MODE_PRIVATE);
2.sp只能获取数据不能对数据进行修改,所以需要使用ShparedPreferences.edit()方法获取可以编辑的对象edit
SharedPreferences.Editor edit=sp.edit();
3.edit是按照键值对的形式存储数据的存储数据的方法是
edit.putString("username",account);
edit.putString("pwd",password);
//commit()方法用于把数据保存到data.xml文件内,不执行commit的话,所有操作不会生效
edit.commit();
4.读取数据的方法是getXxx(),Xxx代表数据类型
//获取sp对象
SharedPreferences sp=context.getSharedPreferences("data",Context.MODE_PRIVATE);
//获取数据,如果没有需要的数据就返回空字符串
String account=sp.getString("username",null);
String password=sp.getString("pwd",null);
5.可以把获取信息的过程写入一个方法内,信息存储在Map内,返回值是Map类型
public static Map<String ,String> getUserInfo(Context context){
//获取sp对象
SharedPreferences sp=context.getSharedPreferences("data",Context.MODE_PRIVATE);
//获取数据,如果没有需要的数据就返回空字符串
String account=sp.getString("username",null);
String password=sp.getString("pwd",null);
//把获取的数据放到map内
Map<String,String> userMap=new HashMap<String,String>();
userMap.put("account",account);
userMap.put("password",password);
return userMap;
}
6.Sharedpreferences存储的数据可以,点击android studio右边的Device File Exploer,路径是/data/data/项目包名/shared_prefs/data.xml内