因此,我有两个屏幕,一个设置密码屏幕和一个输入密码(登录)屏幕。如果没有密码(即从未使用过该应用程序),我希望它弹出输入密码屏幕,然后在启动后进入登录屏幕。如果用户输入密码,它将与共享首选项中存储的值进行比较,如果正确,则继续进入菜单。但是使用设置密码屏幕后,登录屏幕似乎无法访问密码。
如何使登录屏幕看到注册页面设置的密码?
这是创建密码代码:
public class CreatePassword extends Activity {
public EditText setPass1, setPass2;
String newPass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_createpassword);
setPass1 = (EditText)findViewById(R.id.editTextSetPassword);
setPass2 = (EditText)findViewById(R.id.editTextRepeatSetPassword);
}
public void btnSubmitNewPassword(View v){
if(setPass1.getText().toString() != "") {
if (setPass1.getText().toString().equals(setPass2.getText().toString())) {
newPass = setPass1.getText().toString();
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("sharedPref", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putString("password", newPass);
prefEditor.apply();
Toast.makeText(getApplicationContext(), newPass, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "New Password Set", Toast.LENGTH_LONG).show();
startActivity(new Intent(CreatePassword.this, Menu.class));
} else {
Toast.makeText(getApplicationContext(), "Passwords don't match!", Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(getApplicationContext(), "Please Enter Desired Password", Toast.LENGTH_LONG).show();
}
}
}//end CreatePassword class
拒绝使用密码的EnterPassword(登录)屏幕刚刚设置:
public class EnterPassword extends Activity {
EditText editTextPasswordAttempt;
SharedPreferences sharedPref;
String passwordAttempt, passwordActual;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enterpassword);
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
boolean passwordExists = sharedPref.contains("password");
if(passwordExists == false){
startActivity(new Intent(EnterPassword.this, CreatePassword.class));
}
editTextPasswordAttempt = (EditText)findViewById(R.id.editTextPassword);
}
public void btnSubmitToMenu(View v){
passwordActual = sharedPref.getString("password", );
Toast.makeText(getApplicationContext(), passwordActual, Toast.LENGTH_LONG).show();
passwordAttempt = editTextPasswordAttempt.getText().toString();
if(passwordAttempt.equals(passwordActual)) {
startActivity(new Intent(EnterPassword.this, Menu.class));
}
else{
Toast.makeText(getApplicationContext(), "Invalid Password", Toast.LENGTH_LONG).show();
}
}
}
最佳答案
您正在使用2个不同的SharedPreferences。
在CreatePassword
活动中,您可以执行以下操作:
getApplicationContext().getSharedPreferences("sharedPref", MODE_PRIVATE);
但是在
EnterPassword
活动中,您可以执行以下操作:PreferenceManager.getDefaultSharedPreferences(this);
如果您在两个活动中都使用同一行,则该行应该有效。