Ashraf Ashraf - 5 months ago 21
Android Question

Assigning points to each radio button selected

I am currently developing a questionnaire based application where by there are options. I need to assign numerical values to each radio button so when one of it is selected it will give a certain amount of points which will then be used to produce a cumulative amount. I need help in coding the java to do this. any help will be greatly appreciated. Thank you!

int score = 0;
public TextView tv;

public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();

switch (view.getID()) {
case R.id.radioButton1:
if(checked)
score +=1;
break;

case R.id.radioButton2:
if(checked)
score +=1;
break;

case R.id.radioButton3:
if(checked)
score +=3;
break;
}
}

public void updateScore(int score) {
tv = (TextView)findViewById(R.id.textview1);
tv.setText(" " + score);
}


in the XML I have coded a textview with "0" and a text id of
@+id/textview1


the issue is that the score remains at 0 even if any radio buttons are selected

Answer Source

Make the following changes to your code

public TextView tv;
int score = 0;

public void onRadioButtonClicked(View view) {
    boolean checked = ((RadioButton) view).isChecked();

    switch (view.getId()) {   
        case R.id.radioButton1:
            if (checked) {
                score += 1;
            }
            break;

        case R.id.radioButton2:
            if(checked)
                score +=1;
            break;

        case R.id.radioButton3:
            if(checked)
                score +=3;
            break;
    }
    updateScore(score);  // <- Added this line here
}

public void updateScore(int score) {
    // Don't initialise your view here. Take it to onCreate()
    tv.setText(" " + score);
}

EDIT

Is your XML for the radio button similar to what I have here?

<RadioButton
    android:id="@+id/radioButton1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="asas"
    android:onClick="onRadioButtonClicked"/>

Make sure you have added the android:onClick="onRadioButtonClicked" property to each of the radio buttons