-6

i have a TextView which is set using...

// Declare view variables
private TextView mInfoText;

// Assign views from layout file to cor. vars
mInfoText = (TextView) findViewById(R.id.infoText);

how do i do an if else statement for the text inside it, i thought about doing it like this, but it doesn't work, i get a red line under the word "Sand".

if (mInfoText = "Sand"){

                //Show correct

            } else {

                //Show incorrect
            }

Any ideas?

CarlRyds
  • 217
  • 1
  • 5
  • 19
  • 1
    `mInfoText` is a `View`. The view is drawn on your screen. So, you cannot compare a `View` and a `String`. You should get content of the view. Use `mInfoText.getText()`, which will return `String` – GRiMe2D May 05 '16 at 12:45
  • Hint: `TextUtils.equals` – OneCricketeer May 05 '16 at 12:46

5 Answers5

2

You are wanting to compare the value of a TextView to a String. A TextView is not a String, not exacty. Its an object with properties. You need to call getText() to return a String.

Furthermore, you need to use ==, which is an equality check. This will return true or false on the statement. If you use one = it will always be true. One equal sign is used for assignment

if (mInfoText.getText() == "Sand")
element11
  • 3,710
  • 2
  • 15
  • 22
1

You can do this:

if (mInfoText.getText().equals("Sand")){
....
}
dryairship
  • 5,842
  • 2
  • 29
  • 53
0

You will have to do like this.As String Objects should be compared using String#equals method.

if (mInfoText!=null && mInfoText.getText().toString().equals("Sand")){

      //Show correct

} else {

     //Show incorrect
}
Sanjeev
  • 9,798
  • 2
  • 20
  • 33
0

You neded to get the content of the text field using mInfoText.getText() and then compare it usgin equals

if(mInfoText != null && mInfoText.getText().equals("Sand")){
    //Show correct
}else{
    //Show incorrect
}
Guillaume Barré
  • 4,053
  • 2
  • 26
  • 48
-1

= is assignment operator. Use == operator to do comparision of instance.

You should use equals() method to check if contents of two strings are the same.

MikeCAT
  • 69,090
  • 10
  • 44
  • 65
  • not expecting this answer from you as you have that much reputation. Please see question carefully and then post the answer. Author trying to compare string with TextView instance. – Amy May 05 '16 at 12:51