SharedPreferences(共享参数)

//共享参数,多用于自动登录,是 android常用的数据储存的一种,用于储存少量数据,Integer,Double,String等。

public class sharp {
    Context context;                 //接收上下文对象

    public sharp(Context context) { //构造函数
        this.context = context;
    }
//存储数据
    public void read(User user){
        SharedPreferences pre=context.getSharedPreferences("pp",Context.MODE_PRIVATE);          //“pp”为共享文件名
        SharedPreferences.Editor editor=pre.edit();//创建Editor
        editor.putString("id",user.getId());        //把用户名刺入到共享文件里
        editor.putString("pwd",user.getPwd());
        editor.putString("qx",user.getQx());
        editor.commit();
    }
//读取数据
public User write(){ SharedPreferences shp=context.getSharedPreferences("pp",Context.MODE_PRIVATE); String id=shp.getString("name","no");//“no”为默认值 String pwd=shp.getString("pwd","no"); String qx=shp.getString("qx","no"); User user=new User(id,pwd,qx); return user; } }

 

posted on 2016-05-17 10:22  huaihuaibuguai  阅读(272)  评论(0编辑  收藏  举报

导航