I'm working with RadioGroups and nested RadioButtons by programmatically. Creating and removing radio buttons for some behavior. But the problem was revealed, when I fire onCheckedChanged
event. System doesn't reset radio buttons counter, even after, when I'll remove all radio buttons in radioGroup and even after removing RG.
This collision takes place when I'm trying to catch event up such as checks particular radioButton, but I get null point exception because the index of radio button (checkId) doesn't equal the real state.
Should I count radioButtons by myself and correct checkId in onCheckedChanged event?
Looks like crutch.
Some code example here:
private static final String TAG = MainActivity.class.getSimpleName();
private RadioGroup rg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout ll = findViewById(R.id.someLL);
rg = new RadioGroup(this);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Log.d(TAG, "checked id: " + checkedId);
Log.d(TAG, "print text: " + ((RadioButton) group.getChildAt(checkedId)).getText() );
}
});
ll.addView(rg);
rebuildRG(Arrays.asList("one", "two", "three", "four", "five"));
rg.removeAllViews();
rebuildRG(Arrays.asList("111", "222", "333", "444"));
}
private void rebuildRG(List<String> data){
for(String i: data){
RadioButton rb = new RadioButton(this);
rb.setText(i);
rg.addView(rb);
}
}
Logcat here:
D/MainActivity: checked id: 9
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.flexdecision.ak_lex.radiogroup, PID: 11604
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference