How to add radiogroup onchecked listener in Custom Dialog

android, radio-button, radio-group

Solution

You need to use the `Dialog's` reference to get the view's:

Use:

radioQuantity = (RadioGroup) dialog.findViewById(R.id.radioQuantity);
quantity1 = (RadioButton) dialog.findViewById(R.id.quantity1);
quantity2 = (RadioButton) dialog.findViewById(R.id.quantity2);

You get `NullPointerException` as your `RadioGroup` is not attached to the view.

Also for the `CheckedListener` use:

radioQuantity.setOnCheckedChangeListener(new 
   RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {

            if (checkedId == R.id.quantity1) {
                //Your code
            } else if (checkedId == R.id.quantity2) {
                //Your code
            } 

        }
    });

Problem

I have a custom dialog which contains radio buttons, but when I add a oncheckedchangelistener my app crashes. What could be the problem? Thanks in advance! :D This is my code: ``` GridViewAdapter adapter = new GridViewAdapter(alcoholType.this, images,names); gridView.setAdapter(adapter); gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final Dialog dialog = new Dialog(context); dialog.setContentView(R.layout.alcoholdialog); dialog.setTitle("ORDER " + names.get(position)); radioQuantity = (RadioGroup) findViewById(R.id.radioQuantity); quantity1 = (RadioButton) findViewById(R.id.quantity1); quantity2 = (RadioButton) findViewById(R.id.quantity2); radioQuantity.clearCheck(); radioQuantity.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { } }); dialog.show(); } }); ``` This is the error trace: ``` E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.gin.ordering, PID: 22005 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RadioGroup.clearCheck()' on a null object reference at com.example.gin.ordering.alcoholType$1.onItemClick(alcoholType.java:90) at android.widget.AdapterView.performItemClick(AdapterView.java:339) at android.widget.AbsListView.performItemClick(AbsListView.java:1549) at android.widget.AbsListView$PerformClick.run(AbsListView.java:3723) at android.widget.AbsListView$3.run(AbsListView.java:5707) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:145) at android.app.ActivityThread.main(ActivityThread.java:6918) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) ```

Original source