Search code examples
androidandroid-radiogroupandroid-radiobutton

Android RadioGroup/RadioButton Selection - Different in Android API 16/17 - Cannot Select Radiobutton


I'm trying to set the selection of the first radiobutton in a radiogroup. Before I get into the question too deep, I need to mention that the problem ONLY happens in API <= 16. When run on API 17 or above in emulator or real device, everything works perfectly.

What it should do

The RadioButton variable 'first' should point to the first RadioButton that is created earlier in the code. This RadioButton should then be set as checked. As mentioned, the code works fine on API 17 and above (I've seen other issues with API 16, mainly related to drawing and padding, but not this one), and that's why I'm so confused. The logic must be OK or it wouldn't work at all right? But you can see in the logs that a different value is held in 'first' running on each API.

If need be, I'm happy to post more details/logs etc.

The code

//Set the default selection
levelChoices.check(first.getId());
Log.d(TAG, "Which is first:  " + first);
Log.d(TAG, "Which is checked:  " + levelChoices.getCheckedRadioButtonId());

Logs in API 17 or above

Which is first:  android.widget.RadioButton{61c63b2 VFED..C.. ......I. 0,0-
0,0 #1}
Which is checked:  1
//Everything works fine, radio button is selected

Logs in API 16 or below

Which is first:  android.widget.RadioButton@a7886a50
Which is checked:  -1484232112
//No radio button is selected

Solution

  • It looks like, for older Android versions, each RadioButton that is created dynamically must be given an ID using setId. I didn't have to do anything with this, but having it in there meant the RadioButton's were setup correctly, I tested and everything is now working in the older API's.

    It seems my issue was with the RadioGroup's RadioButton's not correctly being added, but as mentioned this only happens pre- API 17.

    There's a similar issue here with the same suggested solution:

    NullPointerException in RadioGroup.setOnCheckedChangeListener in APIS 15 & 16