David Elliott
David Elliott

Reputation: 113

Comparing two EditText values in android

I'm trying to make an app where the user enters a word into an EditText box. Then, they enter something into another box and it checks to see if they are the same word. Here's the code that I used:

         String word = textfield1.getText().toString();
         String answer = textfield2.getText().toString();

          textfield2.setText(textfield2.getText().toString()); 

          if(word == answer){

              Toast.makeText(getApplicationContext(), "correct",
                       Toast.LENGTH_LONG).show();
          }else 
              Toast.makeText(getApplicationContext(), "incorrect", Toast.LENGTH_LONG).show();
       }

However, it always says that the two strings aren't the same even if they are. Is there a way to fix this?

Upvotes: 0

Views: 4681

Answers (5)

Namrata
Namrata

Reputation: 1684

instead of

 if(word.contentEquals(answer)){

     }

Use

 if(word.equals(answer))

as we cant compare strings with Equal to (==) operator

Try This::

String word = textfield1.getText().toString();
             String answer = textfield2.getText().toString();



              if(word.equals(answer)){

                  Toast.makeText(getApplicationContext(), "correct",
                           Toast.LENGTH_LONG).show();
              }else 
                  Toast.makeText(getApplicationContext(), "incorrect", Toast.LENGTH_LONG).show();
           }

Upvotes: 0

Leonardo
Leonardo

Reputation: 3191

I think the best way to do this is using TextUtils:

if(TextUtils.equals(textfield1.getText(),textfield2.getText())){
 //do something
}

Upvotes: 1

SirChristian123
SirChristian123

Reputation: 38

Use:

String word = textfield1.getText().toString();
String answer = textfield2.getText().toString();

if(answer.contentEquals(word)){
  // Do something if equals
}

else{
  // Do something if not equals
}

Upvotes: 1

Alex K
Alex K

Reputation: 8338

You can't compare strings with the == operator.

Use .equals() instead:

if(word.equals(answer)) {
    //do whatever
}

Upvotes: 3

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132972

Use String.equalsIgnoreCase for comparing content of both string variables.:

  if(word.equalsIgnoreCase(answer)){

   }

Upvotes: 2

Related Questions