0

I try to retrieve my RADIOGROUP for check which Radio Button is checked. For this, I use this code in onCreate() :

/**
 * @param savedInstanceState
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    radioGroup_LANGUE = (RadioGroup) findViewById(R.id.RadioGroup_LANGUE);
    radioGroup_MODE = (RadioGroup) findViewById(R.id.RGroup_ModeConnexion);
... }

But I use the debug, and AndroidStudio tell me radioGroup_LANGUE is null. So I get NULLPOINTER EXCEPTION.

In my alertdialog, when user click on OK Button :

.setNegativeButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    radioGroup_LANGUE.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                        public void onCheckedChanged(RadioGroup radioGroup_LANGUE, int checkedId) {
                            // This will get the radiobutton that has changed in its check state
                            RadioButton checkedRadioButton = (RadioButton)radioGroup_LANGUE.findViewById(checkedId);

                            // This puts the value (true/false) into the variable
                            boolean isChecked = checkedRadioButton.isChecked();

                            /// If the radiobutton that has changed in check state is now checked...
                            if (isChecked)
                            {
                                // Changes the textview's text to "Checked: example radiobutton text"
                                Toast.makeText(MainActivity.this,"Checked:" + checkedRadioButton.getText(),Toast.LENGTH_LONG).show();
                            }
                     }
                    });
                }});

My xml :

<RadioGroup
    android:layout_width="148dp"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:id="@+id/RadioGroup_LANGUE">

<RadioButton
        android:layout_width="137dp"
        android:layout_height="wrap_content"
        android:text="@string/Langue_1"
        android:id="@+id/BouttonRADIO_EN"
        android:layout_gravity="center_horizontal"
        android:textSize="20dp"
        android:textStyle="bold" />

<RadioButton
        android:layout_width="137dp"
        android:layout_height="wrap_content"
        android:text="@string/Langue_2"
        android:id="@+id/BouttonRADIO_FR"
        android:layout_gravity="center_horizontal"
        android:textSize="20dp"
        android:textStyle="bold" />

</RadioGroup>

Error log :

06-01 22:51:53.053 21336-21336/com.example.my020571.sterela2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.my020571.sterela2, PID: 21336
java.lang.NullPointerException
   at com.example.my020571.sterela2.MainActivity$4.onClick(MainActivity.java:321)
   at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:170)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:146)
   at android.app.ActivityThread.main(ActivityThread.java:5598)
   at java.lang.reflect.Method.invokeNative(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:515)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
   at dalvik.system.NativeStart.main(Native Method)

LINE 321 :

int selectedID = rGroup_LANGUE.getCheckedRadioButtonId();

METHOD :

private void changerLangue() {

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
            context);


    final View view = View.inflate(MainActivity.this, R.layout.changer_langue, null);


    alertDialogBuilder.setView(view);



    // Titre de la fenêtre
    alertDialogBuilder.setTitle("Langue");
    // set dialog message
    alertDialogBuilder
            .setMessage("Veuillez choisir votre langue :")
            .setCancelable(false)
            .setIcon(R.drawable.logo_langue)

            .setPositiveButton("ANNULER", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // if this button is clicked, close
                    // current activity
                    dialog.cancel();
                }
            })
            .setNegativeButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    int selectedID = rGroup_LANGUE.getCheckedRadioButtonId();
                    RadioButton selectedRadioButton = (RadioButton)findViewById(selectedID);
                    Toast.makeText(getApplicationContext(),selectedRadioButton.getText().toString(),Toast.LENGTH_SHORT).show();
                }});


                            // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();
}
Yvan1263
  • 80
  • 2
  • 14

2 Answers2

1

All of your Views are going to be null without a setContentView in the onCreate.

private void RadioGroup radioGroup_LANGUE;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.YourLayoutFile); // TODO: Replace with your file

    radioGroup_LANGUE = (RadioGroup) findViewById(R.id.RadioGroup_LANGUE);
 }

Another reason they would be null is if you don't use an XML file that contains the @+id/RadioGroup_LANGUE (and other ids you want to find) in the setContentView.


Edit

Since you are using a AlertDialog to show the view, you need to use findViewById on the inflated view instead of on the Activity.

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);

// Get the view for the dialog
final View view = View.inflate(MainActivity.this, R.layout.changer_langue, null);
// Find views within it
rGroup_LANGUE = (RadioGroup) view.findViewById(R.id.RadioGroup_LANGUE);

rGroup_LANGUE.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        RadioButton checkedRadioButton = (RadioButton) group.findViewById(checkedId);

        // TODO: Implement this
}});

// build the dialog
AlertDialog alertDialog = alertDialogBuilder
        .setView(view)      // load the view
        .setTitle("Langue")
        .setMessage("Veuillez choisir votre langue")
        ...
        .setNegativeButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {                
                // Need to use findViewById from the RadioGroup here
                int selectedID = rGroup_LANGUE.getCheckedRadioButtonId();
                String msg = null;
                if (selectedId != -1) {
                    RadioButton selectedRadioButton = (RadioButton)rGroup_LANGUE.findViewById(selectedID);                
                    msg = selectedRadioButton.getText().toString();
                } else {
                    msg = "Nothing selected";
                }
            Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_SHORT).show();
        }})
        .create();

// show it
alertDialog.show();

Sidenote: I don't think setMessage and setView can be used at the same time.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Ohhh thanks a lot @cricket_007. But my radiogroup is in another layout File. So I need choose which layout file please? – Yvan1263 Jun 01 '16 at 19:58
  • The layout file for the dialog, you mean? – OneCricketeer Jun 01 '16 at 20:06
  • Nop. TMy dialog in create in my MainActivity class. But I have create my RadioGroup and so my two RadioButtons in a new XMLFile, called : " changer_langue.xml ". – Yvan1263 Jun 01 '16 at 20:11
  • Ok, well, I'm not sure how you expect to find id's from that layout if it is not loaded to either the current activity or the dialog's view. – OneCricketeer Jun 01 '16 at 20:22
  • Thanks for you help. I think it's because I don't load my custom XML FILE. But I want to know how to correct my error ? – Yvan1263 Jun 01 '16 at 20:27
  • `findViewById` returns null. You are calling `radioGroup_LANGUE.setOnCheckedChangeListener`, so you are invoking a method on a null object, therefore your error. If you get the correct layout and can find the id you want, then it will no longer error at that line – OneCricketeer Jun 01 '16 at 20:30
  • Ok thanks @cricket_007. But I add your code on my code and I get the same error. – Yvan1263 Jun 01 '16 at 20:41
  • That's understandable if you read the last sentence that I wrote in the answer. You haven't shown the full XML file you are using in the Activity, so I don't know what more I can add to solve the problem. – OneCricketeer Jun 01 '16 at 20:44
  • Yes I read again your answer. I check my code, I set again the content view in my onCreate() and I don't know I get always this error. – Yvan1263 Jun 01 '16 at 20:48
  • Probably because `radioGroup_LANGUE.findViewById(checkedId);` is also returning null, my answer was only addressing the error you stated in the question. So, my answer fixed it, and you were getting a new one with the same message, but different code – OneCricketeer Jun 01 '16 at 20:51
  • Thanks, but could you provide what line exactly is 321 of MainActivity.java? – OneCricketeer Jun 01 '16 at 20:57
  • @cricker_007 : Updated. – Yvan1263 Jun 01 '16 at 20:58
  • Ok, so that line of code is nowhere in the code that you have in the question, which is why my first comment here was for a *complete* and *verifiable* example of the problem. Please add your full java file if you must. – OneCricketeer Jun 01 '16 at 21:01
  • I add just my method because my JAVA file have more than 900 lines. – Yvan1263 Jun 01 '16 at 21:04
  • @cricket_007 you making him confusing, this have nothing to do with contentview...waste of time, if he have in dialog radio button, he need to call dialog.findViewById – Milos Lulic Jun 01 '16 at 21:05
  • Hello @MilosLulic ! For you I need to call dialog.findViewById. But what is dialog please? – Yvan1263 Jun 01 '16 at 21:10
  • @McNavy alertDialogBuilder is your view – Milos Lulic Jun 01 '16 at 21:12
  • @MilosLulic : Now I get one mistake with my Toast. NullPointerException lol – Yvan1263 Jun 01 '16 at 21:17
  • @MilosLulic Its due to the selectedID its null. – Yvan1263 Jun 01 '16 at 21:19
1

Try this code with custom dialog:

public void changerLangue(){
        final Dialog mDialog;
        mDialog = new Dialog(MainActivity.this);
        mDialog.setContentView(R.layout.changer_langue);
        Button ok = (Button)mDialog.findViewById(R.id.btn_ok);
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RadioGroup yourRadioGroup=(RadioGroup)mDialog.findViewById(R.id.RadioGroup_LANGUE);
                int selectedID = yourRadioGroup.getCheckedRadioButtonId();
                selectedRadioButton = (RadioButton)mDialog.findViewById(selectedID);
                Toast.makeText(getApplicationContext(),selectedRadioButton.getText().toString(),Toast.LENGTH_SHORT).show();
        });

        Button dismiss = (Button)mDialog.findViewById(R.id.btn_dismiss);
        dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
        mDialog.show();
    }
}

In your changer_langue xml add two buttons btn_ok and btn_dismiss. It works like charm! Cheers

Milos Lulic
  • 627
  • 5
  • 22