0

If I set the text of a TextView in XML, like this:

    <TextView
        ...
        android:text="0" />

Can I compare that string in Java? Doing this:

    private void InitializeMethod() {
        A_1  = tv_1.getText().toString();
    }

    private void CheckAnsMethod() {
        if (A_1 == "0"){
            correctAns.start();
            }
        }else{
            wrongAns.start();
        }
    }

causes the sound 'wrongAns.mp3' to be played...

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Keegs
  • 95
  • 3
  • 11

1 Answers1

1

You needs to use the String class's equals() method:

 if ( "0".equals(A_1) )

"0" == A_1 will compare the values of the references pointing to where the String objects are located. In other words, it's comparing memory addresses when you really want to compare the characters in the strings. The String class's equals() method will actually compare the strings character by character to check if they're equal.

Also, the reason I use "0".equals(A_1) instead of A_1.equals("0") is because if A_1 is ever null for whatever reason, "0".equals(A_1) will not throw a NullPointerException.

Kacy
  • 3,330
  • 4
  • 29
  • 57