SharedPreferences保存用户信息

用户登录的时候,需要将用户名、用户ID等等一些信息保存到APP的文件里面,下次进入APP的时候,先读文件,如果用户已经登录过,则跳过登录界面;
首先,将保存文件的方法写到基类里面,

//保存用户信息
public void saveData(Context context,int userid , int cityid , int shopid , int typeid , String token ,
                     String username){
    SharedPreferences sp = context.getSharedPreferences("config", MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.putInt("userid", userid);
    editor.putInt("cityid",cityid);
    editor.putInt("shopid",shopid);
    editor.putInt("typeid",typeid);
    editor.putString("token",token);
    editor.putString("username",username);
    editor.commit();
}
//判断是不是第一次登陆
public void savefrist(Context context , String isFirstIn){
    SharedPreferences sp = context.getSharedPreferences("config", MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.putString("isFirstIn", isFirstIn);
    editor.commit();
}

在登录界面,进行登录操作的时候,如果操作成功,则保存这些信息,在操作成功之后,加上:

baseactivity.saveData(Login.this,userid , cityid , shopid , typeid, token , username );
baseactivity.savefrist(Login.this,isFirstIn);

在登录的activity的oncreat里面,读取文件,如果文件为空,则直接加载登录界面,如果文件不为空,且能读取到第一次登陆时保存的那个数值,则直接跳转到主界面。

private void isnettestfirst() {
boolean isnet = BaseActivity.isNetworkAvailable(Login.this);
if (isnet == false) {
        setContentView(R.layout.activity_login);
login_instance = this;
        findid();
        click();
        Toast.makeText(Login.this, "请检查你的网络连接", Toast.LENGTH_SHORT).show();
    } else {
myisFirstIn = baseactivity.loadfrist(Login.this);
myusername = baseactivity.loadusername(Login.this);
if ("isFirstIn".equals(myisFirstIn)){
            startActivity(new Intent(Login.this,MainActivity.class));
            finish();
        }else {
            setContentView(R.layout.activity_login);
login_instance = this;
            findid();
            click();
main_login_et_user.setText(myusername);
        }
    }
}
//读取文件里面的内容
public String loadusername(Context context){
    SharedPreferences sp = context.getSharedPreferences("config", MODE_PRIVATE);
    String username = sp.getString("username", "");
return username;
}
//调用读取文件
BaseActivity baseActivity1 = new BaseActivity();
username= baseActivity1.loadusername(this);
//清除文件里面的内容
public void clear(Context context) {
    SharedPreferences sp = context.getSharedPreferences("config", MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.remove("isFirstIn");
    editor.remove("userid");
    editor.remove("cityid");
    editor.remove("shopid");
    editor.remove("typeid");
    editor.remove("token");
    editor.commit();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值