SharedPreferences数据存储类的简单使用

来源:互联网 发布:unity3d格式 解包 编辑:程序博客网 时间:2024/05/18 00:24


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();
原创粉丝点击