3

Possible Duplicate:
How do I compare strings in Java?
why equals() method when we have == operator?

All I'm trying to do here is to compare a text that was entered in a text-field widget with a given string ("abc") and then set the button-text to either "wrong pass" or "pass ok". However, the button-text is always set to "wrong pass" even if I enter the correct "password". What am I doing wrong?

public class FullscreenActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_start);

    final Button button = (Button) findViewById(R.id.button);
    final EditText textedit = (EditText) findViewById(R.id.textedit);

    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            if (textedit.getText().toString() == "abc") 
                button.setText("pass ok"); // doesn't work
            else 
                button.setText("wrong pass");

        }
    });
}

...
Community
  • 1
  • 1
Đinh Carabus
  • 3,403
  • 4
  • 22
  • 44

3 Answers3

9

one issue is:

if (textedit.getText().toString() == "abc") 

should be

if (textedit.getText().toString().equals("abc") )

even better:

 if ("abc".equals(textedit.getText().toString()))

It is always better to use equals() while comparing String/Objects instead of using ==

== checks for reference equality. equals() check for content equality.

kosa
  • 65,990
  • 13
  • 130
  • 167
4

You cannot compare String in Java / Android with ==, you must use equals():

if (textedit.getText().toString().equals("abc")) 

You can find a good explanation of why in: How do I compare strings in Java?

Community
  • 1
  • 1
Sam
  • 86,580
  • 20
  • 181
  • 179
4

Try this, using "equals".

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    final Button button = (Button) findViewById(R.id.btnLogin);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
        EditText getpass = (EditText)findViewById(R.id.textedit);

            String pass = getpass.getText().toString();

            if(pass.equals("abc")){
                Toast toast = Toast.makeText(getApplicationContext(), "pass ok", Toast.LENGTH_SHORT);
                toast.show();



            }else{
                Toast toast = Toast.makeText(getApplicationContext(), "wrong pass", Toast.LENGTH_SHORT);
                toast.show();
            }
        }
    });

}
Marcos Aguayo
  • 6,840
  • 8
  • 28
  • 61