android基础笔记——模板代码:SharedPreferences保存、读取数据

来源:互联网 发布:mysql 触发器 可靠性 编辑:程序博客网 时间:2024/06/05 14:34

一、保存数据

1、通过上下文获得SharePreference对象

SharedPreferences sp = context.getSharedPreferences("SharePreference", context.MODE_PRIVATE);
2、获得一个编辑对象
Editor edit = sp.edit();
3、存数据
edit.putString("number", number);
edit.putString("password", password);
4、 提交数据

edit.commit();


二、读取数据

1、通过上下文获得SharePreference对象
SharedPreferences sp = context.getSharedPreferences("SharePreference", context.MODE_PRIVATE);
2、getString(关键字,默认值)方法,读取内容
String number = sp.getString("number", null);
String password = sp.getString("password", null);
3、判断是否为空
if (!TextUtils.isEmpty(number) && !TextUtils.isEmpty(password)) {
4、new一个HashMap
Map<String, String> userInfoMap = new HashMap<String, String>();
5、将读取到的值保存到集合
userInfoMap.put("number", number);
userInfoMap.put("password", password);

}


完整代码:

public static boolean SaveUserInfo(Context context, String number, String password) {try {// 通过上下文获得SharePreference对象SharedPreferences sp = context.getSharedPreferences("SharePreference", context.MODE_PRIVATE);// 获得一个编辑对象Editor edit = sp.edit();// 存数据edit.putString("number", number);edit.putString("password", password);// 提交数据edit.commit();return true;} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return false;}public static Map<String, String> getUserInfo(Context context) {//通过上下文获得SharePreference对象SharedPreferences sp = context.getSharedPreferences("SharePreference", context.MODE_PRIVATE);//getString(关键字,默认值)方法,读取内容String number = sp.getString("number", null);String password = sp.getString("password", null);//判断是否为空if (!TextUtils.isEmpty(number) && !TextUtils.isEmpty(password)) {//new一个HashMapMap<String, String> userInfoMap = new HashMap<String, String>();//将读取到的值保存到集合userInfoMap.put("number", number);userInfoMap.put("password", password);return userInfoMap;}return null;}






原创粉丝点击