Search code examples
androidandroid-alertdialogandroid-radiogroup

How do I read the value of my RadioGroup in an AlertDialog?


So I am using AlertDialog to display my RadioGroup and I want to get the value of the RadioButton to be pass to my next method. However when I run the program it returns an error:

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.RadioGroup.getCheckedRadioButtonId()' on a null object reference

How do I fix this ?

private void showChoosePackage() {

    AlertDialog.Builder builder = new AlertDialog.Builder(descriptionsActivity.this);
    LayoutInflater inflater = this.getLayoutInflater();
    View choose_package_layout = inflater.inflate(R.layout.choose_package_layout, null);

    builder.setView(choose_package_layout);
    final  AlertDialog dialog = builder.create();

    radioGroup = findViewById(R.id.radio_grp);
    Button btnApply = choose_package_layout.findViewById(R.id.button_apply);

    final RadioButton rdibtn = (RadioButton)choose_package_layout.findViewById(R.id.radio1);
    final RadioButton rdibtn2 = (RadioButton)choose_package_layout.findViewById(R.id.radio2);

    rdibtn.setText(Common.longhousedesc.PackageOne);
    rdibtn2.setText(Common.longhousedesc.PackageTwo);

    btnApply.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            int Selectedid = radioGroup.getCheckedRadioButtonId();
            radioButton = findViewById(Selectedid);

            showConfirmDialog(radioButton.getText());
        }
    });

    builder.show();

}

Solution

  • You need to specify the view when finding the radio group:

    radioGroup = choose_package_layout.findViewById(R.id.radio_grp);