1. Download our Official Android App: Forums for Android!

Apps if() statement not being entered

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

  1. Slaine82

    Slaine82 Newbie
    Thread Starter
    Rank:
    None
    Points:
    15
    Posts:
    10
    Joined:
    Aug 1, 2011

    Aug 1, 2011
    10
    0
    15
    Software Developer
    Dublin, Ireland
    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!
     

    Advertisement

  2. dCoder

    dCoder Newbie
    Rank:
    None
    Points:
    16
    Posts:
    13
    Joined:
    Jul 18, 2010

    Jul 18, 2010
    13
    3
    16
    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
    Rank:
    None
    Points:
    53
    Posts:
    363
    Joined:
    Jun 12, 2010

    Jun 12, 2010
    363
    57
    53
    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
    Rank:
    None
    Points:
    15
    Posts:
    10
    Joined:
    Aug 1, 2011

    Aug 1, 2011
    10
    0
    15
    Software Developer
    Dublin, Ireland
    Thanks both!
     

Share This Page

Loading...