我正在创建一个Android应用程序,将打开的第一个活动将是一个密码输入。要知道密码已经在变量中设置了值“admit”。我创建了一个if语句来检查用户输入了什么值,然后将其与变量进行比较,如果值匹配则转到主屏幕,但是它一直说它是错误的密码。任何人都可以查看我的代码,并建议我出错了。
public class Password extends ActionBarActivity implements View.OnClickListener {
protected String password = "admin";
String getPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_password);
Button passwordButton = (Button) findViewById(passwordbutton);
EditText passwordInput = (EditText) findViewById(R.id.password);
getPassword = (passwordInput.getText().toString());
passwordButton.setOnClickListener(this);
}
public void onClick(View v) {
if (getPassword.equals(password)) {
Intent goHome;
goHome = new Intent(this, home.class);
startActivity(goHome);
} else {
AlertDialog.Builder wrongPasswordBuilder = new AlertDialog.Builder(this);
wrongPasswordBuilder.setTitle(getString(R.string.wrongPasswordTitle));
wrongPasswordBuilder.setMessage(getString(R.string.wrongPasswordTryAgain));
wrongPasswordBuilder.setPositiveButton("ok", null);
AlertDialog dialog = wrongPasswordBuilder.show();
}
}
答案 0 :(得分:2)
如果在onCreate()中写入passwordInput.getText()。toString(),它总是返回空字符串。所以在onClick()中写下这些行。代码写在下面
public void onClick(View v) {
getPassword = passwordInput.getText().toString()
if (getPassword.equals(password)) {
Intent goHome;
goHome = new Intent(this, home.class);
startActivity(goHome);
} else {
AlertDialog.Builder wrongPasswordBuilder = new AlertDialog.Builder(this);
wrongPasswordBuilder.setTitle(getString(R.string.wrongPasswordTitle));
wrongPasswordBuilder.setMessage(getString(R.string.wrongPasswordTryAgain));
wrongPasswordBuilder.setPositiveButton("ok", null);
AlertDialog dialog = wrongPasswordBuilder.show();
}
}
答案 1 :(得分:1)
将getPassword = passwordInput.getText().toString();
放在OnClickListener
中。现在,您的变量getPassword
正在onCreate
方法中设置,因此它将始终设置为EditText
的默认值。相反,您需要在每次按下按钮时更新变量。
答案 2 :(得分:1)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_password);
Button passwordButton = (Button) findViewById(passwordbutton);
EditText passwordInput = (EditText) findViewById(R.id.password);
passwordButton.setOnClickListener(this);
}
public void onClick(View v) {
//Place the getPassword variable in the onClick method. That way it's stored everytime you click it.
getPassword = (passwordInput.getText().toString());
if (getPassword.equals(password)) {
Intent goHome;
goHome = new Intent(this, home.class);
startActivity(goHome);
} else {
AlertDialog.Builder wrongPasswordBuilder = new AlertDialog.Builder(this);
wrongPasswordBuilder.setTitle(getString(R.string.wrongPasswordTitle));
wrongPasswordBuilder.setMessage(getString(R.string.wrongPasswordTryAgain));
wrongPasswordBuilder.setPositiveButton("ok", null);
AlertDialog dialog = wrongPasswordBuilder.show();
}
}