Android Dialog/AlertDialog getButton NullPointerException

April 21, 2019

Bump into NullPointerExeption when calling AlertDialog.getButton(AlertDialog.BUTTON_POSITIVE)

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference

Well, you can only access getButton after AlertDialog.show is called.

If you are using DialogFragment, you can access the button at onStart.

class LocationPickerDialog : DialogFragment() {

    private val okButton: Button by lazy {
        (dialog as AlertDialog).getButton(AlertDialog.BUTTON_POSITIVE)
    }
    private val cancelButton: Button by lazy {
        (dialog as AlertDialog).getButton(AlertDialog.BUTTON_NEGATIVE)
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val customView = activity!!.layoutInflater.inflate(R.layout.dialog_location_picker, null)

        val builder = AlertDialog.Builder(context!!)
                // .setTitle(title)
                // .setMessage("Do Something!")
                .setView(customView)
                /*
                .setPositiveButton(android.R.string.ok) { _, _ ->
                    // do something
                }
                .setNegativeButton(android.R.string.cancel) { _, _ ->
                    // do something
                }
                 */
                .setPositiveButton(android.R.string.ok, null)
                .setNegativeButton(android.R.string.cancel, null)
        val dialog = builder.create()

        // access button here will trigger NullPointerException
        // val okButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE)
        // okButton.isEnabled = false

        return dialog
    }

    override fun onStart() {
        super.onStart()

        okButton.setOnClickListener {
            // do something
        }

        cancelButton.setOnClickListener {
            // do something
        }

        okButton.isEnabled = false
        cancelButton.isEnabled = false
    }
}

NOTE: You can access the button at dialog.setOnShowListener callback as well.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.