Android Dialog/AlertDialog getButton NullPointerException

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.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.