Daniel Scocco
Daniel Scocco

Reputation: 7266

Android: IF statement with radio buttons not working

I am trying to make a quiz app, so there are 5 radio buttons with possible answers, and only 1 is correct. Then there's a submit button, which has an onClick="clickMethod" to process the submission.

My clickMethod looks like this:

public void clickMethod(View v){
                RadioGroup group1 = (RadioGroup) findViewById(R.id.radioGroup1);
                int selected = group1.getCheckedRadioButtonId();
                RadioButton button1 = (RadioButton) findViewById(selected);
                if (button1.getText()=="Right Answer")
                    Toast.makeText(this,"Correct!",Toast.LENGTH_SHORT).show();
                else
                    Toast.makeText(this,"Incorrect.",Toast.LENGTH_SHORT).show();
    }

However I can't get the IF statement to work no matter what. If I try to make the toast with "button1.getText()" as parameter it does print the "Right Answer" string, but for some reason inside the IF statement it's not working, and the ELSE is always executed even when I check the right answer.

Does anyone know what might be happening or a better way to do this?

Upvotes: 2

Views: 2247

Answers (4)

Cata
Cata

Reputation: 11211

If you want to compare objects in Java you have to use equals() method and not the == operator ..

if (button1.getText().toString().equals("Right Answer")) {
 Toast.makeText(this,"Correct!",Toast.LENGTH_SHORT).show();
} else {
 Toast.makeText(this,"Incorrect.",Toast.LENGTH_SHORT).show();
}

Upvotes: 1

flo
flo

Reputation: 2018

In Java you can't compare Strings with == you have to use equals():

if (button1.getText().equals("Right Answer"))

Upvotes: 1

twaddington
twaddington

Reputation: 11645

You should use the equals String method for String comparison:

public void clickMethod(View v){
    RadioGroup group1 = (RadioGroup) findViewById(R.id.radioGroup1);
    int selected = group1.getCheckedRadioButtonId();
    RadioButton button1 = (RadioButton) findViewById(selected);
    if ("Right Answer".equals(button1.getText())) {
        Toast.makeText(this,"Correct!",Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(this,"Incorrect.",Toast.LENGTH_SHORT).show();
    }
}

Upvotes: 2

Tim
Tim

Reputation: 35933

You're not comparing strings correctly.

The == operator is used when we have to compare the String object references. If two String variables point to the same object in memory, the comparison returns true. Otherwise, the comparison returns false. Note that the ‘==’ operator does not compare the content of the text present in the String objects. It only compares the references the 2 Strings are pointing to.

Read here: http://www.javabeginner.com/learn-java/java-string-comparison

Upvotes: 3

Related Questions