-23

I am trying to check if text in editText is equal to some string. This is my if statement (it comes every time I press a button):

if(tx.getText().toString()=="bla")

This is tx: tx=(EditText)findViewById(R.id.editText1);

I don't know why but the if is never true. I tried to check it by toast this way:

Toast.makeText(getApplicationContext(),tx.getText().toString(), Toast.LENGTH_LONG).show();

And it is "bla" but still its false. Why?

Shawn Hemelstrand
  • 2,676
  • 4
  • 17
  • 30

3 Answers3

4

You should use equals

if(tx.getText().toString().equals("bla"))

equals compares the string, but == compares the objects.

As @Frank suggested in order to avoid NPE compare like this

if("bla".equals(tx.getText().toString()))
Pragnani
  • 20,075
  • 6
  • 49
  • 74
  • 1
    and put the "bla" literal first, avoid nullpointers.. – Frank Mar 24 '13 at 18:37
  • thank you very much. im sorry for this stupid question i will try to search more next time, i tought this is something more complex. –  Mar 24 '13 at 18:42
1

You have not use "==" for testing equality of two strings.Use equals method of String class.

hasanghaforian
  • 13,858
  • 11
  • 76
  • 167
1

When you compare two String objects, you don't compare their literal value. You check if they are the same object, which is usually not the case. That's why you want to use mystring.equals("my string litereal") instead.

NullData
  • 394
  • 2
  • 8