0

I'm showing a DialogFragment when a user clicks on the Customize button for an item.

btnCustomize.setOnClickListener(new View.OnClickListener(){
    @Override public void onClick(View v){
        CustomDialog dialog = new CustomDialog();
        FragmentManager manager = ((Activity) context).getFragmentManager();
        dialog.show(manager,"tag");
        // the line below throws null pointer exception
        Button btnCustomConfirm = v.findViewById(R.id.btnCustomConfirm);
        btnCustomConfirm.setOnClickListener(new View.OnClickListener(){
            @Override public void onClick(View v){
                //
            }
        });
    }
}

In the dialog's xml layout file there is a Button btnCustomConfirm, but the line btnCustomConfirm.setOnClickListener(...) throws nullpointerexception:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

  • https://stackoverflow.com/questions/18601049/adding-positive-negative-button-to-dialogfragments-dialog – Atiq May 27 '18 at 12:57
  • Move `findViewById` to `onCreate`,and why do you have to put one `onClick` inside of another? – Suleyman May 27 '18 at 15:24
  • The DialogFragment shows some CheckBoxes for the user to choose options, and when the user clicks OK on the dialog I want to iterate through the CheckBoxes to see which ones are checked. So I'm trying to just make an onClickListener for that OK button, and put the logic inside that. The first onClick is when the user clicks on the "customize" button, which triggers the dialog to open. –  May 27 '18 at 15:30
  • Ok then, did you try to move `findViewById` to `onCreate`? Basically you error means that the button is null, so it's not initialised when `setOnclickListener` is called. – Suleyman May 27 '18 at 15:40
  • I got it working by using a regular AlertDialog.Builder instead of DialogFragment. With AlertDialog the setOnClickListener works fine –  May 27 '18 at 16:53

1 Answers1

1

Try changing the line to

Button btnCustomConfirm = v.findViewById(R.id.btnCustomConfirm);

Also, I assume that you have a button with id btnCustomConfirm in the dialog's XML layout.

Huzaifa Iftikhar
  • 755
  • 1
  • 6
  • 9
  • that fixes the first null pointer exception, but then btnCustomConfirm.setOnClickListener(...) throws error (...null object reference) –  May 27 '18 at 13:18