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();
}
發佈了61 篇原創文章 · 獲贊 72 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章