1. Are you ready for the Galaxy S20? Here is everything we know so far!

if() statement not being entered

Discussion in 'Android Development' started by Slaine82, Aug 6, 2011.

  1. Slaine82

    Slaine82 Newbie
    Thread Starter

    Hi All,

    I am having a problem which is driving me crazy :thinking:, I am sure it is something simple but I just can't see what it wrong.

    Basically I am having a problem with an if statement not being entered after using a equals statement even though both side match exactly, the code I have is

    String currentQCorAns = correctAnswers[currentQNo];
    //this pulls in an answer from an array in the resources value is "Hill Of Tara"
    String currentSelectedString = (String)(selectedRadioButton.getText());
    //this gets the current selected radio buttons text value is "Hill Of Tara"

    if(currentQCorAns == currentSelectedString ){
    Toast.makeText(mContext, "Question is correct", Toast.LENGTH_SHORT).show();
    } else {
    Toast.makeText(mContext, "Question is incorrect", Toast.LENGTH_SHORT).show();
    }

    I have tried everything from casting the variables to the same type to be sure. Even the following doesn't work:-

    if(currentQCorAns == "Hill Of Tara")

    It always enters the else part of the block. Can anyone help? Is it something to do with the fact I am pulling in the values from a resources file.

    Thanks!
     



    1. Download the Forums for Android™ app!


      Download

       
  2. dCoder

    dCoder Newbie

    You should not use "==" when comparing two Strings. You should use the equals() method.

    if (currentQCorAns.equals(currentSelectedString)) {...}

    The == operator compares the reference variables, which are different.
     
    Slaine82 likes this.
  3. JiMMaR

    JiMMaR Android Enthusiast

    in general , do not compare objects with the == , use .equals()
    also .. when posting a code .. use the
    Code (Text):
    1.  tag
     
    Slaine82 likes this.
  4. Slaine82

    Slaine82 Newbie
    Thread Starter

    Thanks both!
     
Loading...
Similar Threads - statement being entered
  1. Jerome Viviano
    Replies:
    1
    Views:
    289
  2. Smailliw
    Replies:
    2
    Views:
    805
  3. FireMarshalBill
    Replies:
    2
    Views:
    725
  4. SUPER_JERK
    Replies:
    1
    Views:
    748
  5. Dave Estam
    Replies:
    8
    Views:
    1,890
  6. Milo Williamson
    Replies:
    0
    Views:
    1,035
  7. scottdave
    Replies:
    3
    Views:
    1,395
  8. Dave784
    Replies:
    3
    Views:
    1,134
  9. dorlow
    Replies:
    3
    Views:
    1,829
  10. lovingdog
    Replies:
    1
    Views:
    2,341

Share This Page

Loading...