Search code examples
javaandroidloopsradio-buttononclicklistener

android.widget.RadioGroup cannot be cast to android.widget.RadioButton


I've created pragmatically 5 radio groups with 4 radio buttons each. When I am trying to use checkedRadioButton the emulator crushes? The error is: android.widget.RadioGroup cannot be cast to android.widget.RadioButton. Where am I wrong?

Here is my code:

    radioGroup = new RadioGroup[5];
    answer = new RadioButton[4];
    int i = 0;
    for (Question qn : questions) {
        radioGroup[i] = new RadioGroup(this);
        radioGroup[i].setId(i);
        int j = 0;
        for (Answer an : answers) {
            if (qn.getID() == an.getQuestion_id_answer()) {
                answer[j] = new RadioButton(this);
                answer[j].setText(an.getAnswer());
                answer[j].setId(j);
                radioGroup[i].addView(answer[j]);

                answer[j].setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        int checkedRadioButtonId = v.getId();
                        Toast.makeText(getApplicationContext(), "Checkbox" + checkedRadioButtonId + " checked", Toast.LENGTH_SHORT).show();
                        RadioButton checkedRadioButton = (RadioButton) findViewById(checkedRadioButtonId);
                    }
                });
                j++;
            }
        }
        linearLayout.addView(radioGroup[i]);
        i++;
    }

Solution

  • You are setting the id for the RadioGroup as well as the RadioButton views programmatically by

    radioGroup[i].setId(i);
    

    respectively

    answer[j].setId(j);
    

    Because some values of the i's can also be values for the j's (e.g. i=j=0), you sometimes assign the same id twice.

    The method findViewById() will return any View with matching id, the returned View is only after that cast to the appropriate class.

    Now accidentally in the line

    RadioButton checkedRadioButton = (RadioButton) findViewById(checkedRadioButtonId);
    

    the RadioGroup with the requested id 'checkedRadioButtonId' is found first. This causes the crash.

    To solve the problem, use the tag attribute, for example

    radioGroup[i].setTag("rg" + i); and answer[j].setTag("rb" + j);

    Then you can get the individual View with tag "xyz" by writing

    RadioButton checkedRadioButton = (RadioButton) findViewWithTag("xyz");