0

I am trying to compare the text of a button to decide on the course of action to take in this Android app I am making. I am getting some unexpected behavior that I do not understand.

  clickMeButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (v.getId() == R.id.btnLeft) {
                Button button = (Button) v;
                String click = new String("Click me");
                String look = new String(button.getText().toString());
                Boolean check = new Boolean(look == click);
                if (button.getText().toString() == "Click me") {

Variable check is returning false. Why? In debugger, both items have "Click me" listed next to them. The button I click in the emulator says "Click me" and its original text, "Click me" is specified by the xml.

Jack Frye
  • 583
  • 1
  • 7
  • 28

2 Answers2

5

That is not how we do string comparison in Java. Try this

if (button.getText().toString().equals("Click me")) {

== checks if both parameters are same object while equals() check if both parameters have same value.

Rohit5k2
  • 17,948
  • 8
  • 45
  • 57
1

If you compare string object to string object this will ok. But you are comparing a object with char array. An object never be == to a char array. Object value can be equal but object compare will return false. Because this 2 variables not same. In java best practice of comparing strings is equal method.

Boolean check = new Boolean(look == click); // DO NOT
Boolean check = new Boolean(look.equals(click)); // DO

It's same for the if statement.

if (button.getText().toString().equals(click)){..}

Edit: And here is a good explanation How do I compare strings in Java?

Community
  • 1
  • 1
Eren Utku
  • 1,731
  • 1
  • 18
  • 27