記住密碼這個功能大家應該都不陌生,所以在思考邏輯的時候會比較清楚一點,也可以較熟悉SharedPreferences的應用,這個特別的地方是我設了一個boolean狀態給後續執行可以做出判斷,以下是我的做法:
public class Login extends AppCompatActivity {
private EditText account,password,code;
private CheckBox remember;
private String Account,Password,Account2,Password2 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
account =findViewById(R.id.account2);
password=findViewById(R.id.password2);
code=findViewById(R.id.code);
check=findViewById(R.id.remember);
output(); //先執行我寫的副程式,可以先參考
Button login = findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() { //點擊登入按鈕
@Override
public void onClick(View view) {
Account2=account.getText().toString(); //取得輸入的值並轉成字串
Password2=password.getText().toString();
SharedPreferences user =getSharedPreferences("signup",MODE_PRIVATE);
Account=user.getString("account","");
Password=user.getString("password",""); //取得之前註冊好的資料
if (TextUtils.isEmpty(Account2)){
Toast.makeText(Login.this, "請輸入帳號", Toast.LENGTH_SHORT).show();
}else if(TextUtils.isEmpty(Password2)) {
Toast.makeText(Login.this, "請輸入密碼", Toast.LENGTH_SHORT).show();
}else if(Account2.equals(Account) &&
Password2.equals(Password)){
Intent intent = new Intent();
intent.setClass(Login.this, Menu.class); //若帳密皆符合先前註冊資料則跳頁
startActivity(intent);
input(); ///登入成功的話才執行這個副程式
}else {
Toast.makeText(Login.this, "輸入有誤,請重新確認", Toast.LENGTH_SHORT).show();
account.setText(""); //清空
passsword.setText("");
}
}
});
}
private void input() {
SharedPreferences user = getSharedPreferences("remember", MODE_PRIVATE);
SharedPreferences.Editor edit = user.edit();
if (check.isChecked()) { //如果記住密碼那個選項有打勾就把這次成功登入的資料儲存起來
edit.putString("account2",account.getText().toString());
edit.putString("password2",password.getText().toString());
edit.putBoolean("remember",true); //把我自己設的remember狀態設為true
} else {
edit.remove("account2"); //若上次沒打勾就把它清除記住的資料
edit.remove("password2");
edit.putBoolean("remember",false);
}
edit.commit();
}
private void output(){
SharedPreferences user =getSharedPreferences("remember",MODE_PRIVATE);
String account2=user.getString("account2",""); //若沒取得就是沒任何東西 " "
String password2=user.getString("password2","");
boolean remember=user.getBoolean("remember",false);
//在input()我是寫成若打勾則讓它remember設為true,所以若沒取到則是false
account.setText(account2); //有取到先前給予的資料的話就會顯示出來
password.setText(password2);
remember.setChecked(remember);//並且利用remember的狀態判斷上次是否打勾,有的話就顯示打勾
}
}