SharedPreferences是一个比较轻量级数据存储类,用于存储偏好信息,例如app用户的登录用户名和密码,便于下次登录时判断用户时候可以直接进入app,或者断网登录等,下面是SharedPreferences的简单用法。
本人在MainActivity.java类的onCreate()方法中做了一个简单测试,代码如下。
//参数一:文件名称,参数二:私人文件,只能本程序读取 SharedPreferences pre = getApplicationContext().getSharedPreferences("userInfo",MODE_PRIVATE); SharedPreferences.Editor editor = pre.edit(); editor.putString("username","zhangsan"); editor.putString("password","123456"); editor.putBoolean("isLogin",true); //存储完需提交 editor.commit(); //第二个参数为默认值,如果没有值就会给默认值 String username = pre.getString("username",null); String pwd = pre.getString("password",null); boolean isLogin = pre.getBoolean("isLogin",false); System.out.println("密码是:"+pwd); //删除某个值 //editor.remove("password"); //清除所有数据 //editor.clear(); //删除完之后也要提交改变 editor.commit();