Soatl
Soatl

Reputation: 10592

Android dialog.getButton(AlertDialog.BUTTON_POSITIVE) Null Pointer

I cannot get dialog.getButton(AlertDialog.BUTTON_POSITIVE) to work. I always get a null pointer exception, even though I use the .setPositiveButton() method. I saw that this was an issue in FroYo, but I am on V 4.4. I haven't seen any logged problems with this so I have no clue what the issue is

Code:

AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this)
        .setTitle(R.string.delete_db_on_exit)
        .setCustomTitle(dialogView)
        .setPositiveButton(R.string.confirm_button_text, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                if (((CheckBox) dialogView.findViewById(R.id.confirm_delete_checkbox)).isChecked()) {
                    _application.setDeleteDatabaseOnExit();
                    dialog.cancel();
                    //Navigate back to main activity
                    Intent mainActivityIntent = new Intent(AdministrationActivity.this, MainActivity.class);
                    startActivityForResult(mainActivityIntent, 1);
                } else {
                    Toast.makeText(context, "Please click the confirmation checkbox before continuing", Toast.LENGTH_LONG).show();
                }
            }
        });
dialog = dialogBuilder.create();
Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
positiveButton.setEnabled(false);

Upvotes: 0

Views: 1675

Answers (1)

Mike M.
Mike M.

Reputation: 39191

The Views in a Dialog aren't created until the Dialog is actually shown; that is, until you call dialog.show(). The create() method name is a little misleading. If you try to get a reference to the Positive button before then, it will return null. Move the Button positiveButton... code block to after your call to dialog.show().

Upvotes: 1

Related Questions