-2

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
Aleksey Kabanov
  • 347
  • 1
  • 2
  • 8

1 Answers1

1

You are trying to use checkedId as position .See in line below.

((RadioButton) group.getChildAt(checkedId))

Its clearly mentions in callback that its ID not position. See.

@Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
      //checkedId :- xml id of currently checked radio Button   
    }

And

getChildAt(int index) :- getChildAt() takes index as argument not ID

Solution is

 ((RadioButton) group.findViewById(checkeId)).getText();

Or Simply.

((RadioButton)findViewById(checkeId)).getText();
ADM
  • 20,406
  • 11
  • 52
  • 83