SharedPreferences保存用户信息

来源:互联网 发布:程序员求职成功 编辑:程序博客网 时间:2024/05/09 18:59

用户登录的时候,需要将用户名、用户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();}
0 0