2

I am trying to check a string value in if but it always is entering the else, what Is wrong here? Thank you

public void alertBtn(View v){
    EditText text = (EditText)findViewById(R.id.editText1);
    String value = text.getText().toString();
    String password="asd";
    if (value==password){

            new AlertDialog.Builder(this)
            .setTitle("Success")
            .setMessage("Correct Password")
            .setNeutralButton("OK", null)
            .show();
        }
    else
        new AlertDialog.Builder(this)
        .setTitle("Error")
        .setMessage("Wrong password")
        .setNeutralButton("OK", null)
        .show();



}

4 Answers4

2

Using the == operator will compare the references to the strings not the string themselves.

String value = text.getText().toString();
String password="asd";

if (value.equals(password))
{
}
Basbous
  • 3,927
  • 4
  • 34
  • 62
1

Use .equals or .equalsIgnoreCase() to compare strings

What is the difference between == vs equals() in Java?

 if (value.equals(password)){

Also move the initialization of editText to onCreate. There is no need to initialize edittext everytime on button click

  text = (EditText)findViewById(R.id.editText1); // in onCreate

and declare EditText text as class member

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
1

use equals() function

Try

if( value.equals(password) ) {

}
Tamil Selvan C
  • 19,913
  • 12
  • 49
  • 70
0

Look here

Use the String.equals(String other) function to compare strings, not the == operator.

The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with ==, but it's better not to rely on that.

Community
  • 1
  • 1
Christian
  • 13
  • 5