I have a simple password protection. I do it like this:
EditText editText1 = (EditText) findViewById(R.id.editText1);
String Password = editText1.getText().toString();
if(Password == "a"){
Toast.makeText(getApplicationContext(), "Success" + Password, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Failure" + Password, Toast.LENGTH_SHORT).show();
}
I have edittext and button. If user is typing in "a", toast should say success. But it is always saying failure. I don't understand what is wrong in my code...
In Java, using ==
for non-primitive expressions will always compare object references. You're asking whether Password
refers to the exact same object as the string literal "a".
Use either:
if (Password.equals("a"))
or
if ("a".equals(Password))
These will call the String.equals(Object)
override, which determines whether two references refer to equal String objects - i.e. the same logical sequence of characters.
The former will throw an exception if Password
is null; the latter won't. Don't treat this as a suggestion to always use the latter form - if Password
shouldn't be null, then an exception may well be better than continuing in an unexpected state.
I'd also encourage you to be consistent with your variable names - typically local variables are camelCased, so you'd use password
instead of Password
.
You need to use equals method. Not ==
for comparison of strings. So, you should be doing -
if( Password.equals("a") )
{
// ....
}
string::equals reference
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With