I asked this question yesterday (http://stackoverflow.com/questions/7392321/how-do-you-disable-a-button-inside-of-an-alertdialog) and modified my code accordingly... this mornin
You have two problems. The first is that you should be calling show()
and create()
separately like that. What you've actually done is implicitly create one AlertDialog and display it with alertbox.show()
, and then right below it create a second AlertDialog
that you are using to manipulate the button. Let's try to keep the direct calls to the Builder at a minimum.
Also, and the more direct reason for your NPE crash, in AlertDialog
land the buttons themselves don't actually get created until the AlertDialog
is prepared for display (basically, after AlertDialog.show()
is called...again, not to be confused with the AlertDialog.Builder.show()
method). In order to use AlertDialog
for your purposes, you need to obtain and manipulate the button state after displaying the dialog. Here is a modification of your final code section that fixes this:
//Create the AlertDialog, and then show it
AlertDialog dialog = alertbox.create();
dialog.show();
//Button is not null after dialog.show()
Button button = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
if(monsterint > playerint) {
button.setEnabled(false);
}
HTH
EDIT
At first I thought the code should read:
AlertDialog dialog = alertbox.create();
Button button = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
if(monsterint > playerint) {
button.setEnabled(false);
}
dialog.show();
And I would expect this to work, however no matter how you cook this piece of code, the call to getButton(int which) always returns null.
There doesn't seem to be any sensible reason for this. I am tempted to say that this is a bug in the API. I targeted it for API level 8.
UPDATE
Congratulations you have discovered Android Bug #6360 see comment #4 for a workaround
Also you could take a look at a possible indirect duplicate of this question
And the solution is to call getButton after dialog.show()
:
AlertDialog dialog = alertbox.create();
dialog.show();
Button button = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
if(monsterint > playerint) {
button.setEnabled(false);
}
i tryed these code and it work's you need to hid first show ok
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setMessage("You have Encountered a Monster");
alertbox.setPositiveButton("asdasd", null);
alertbox.show();
alertbox.setPositiveButton("", null);
alertbox.show();
The trick is that you need to use the AlertDialog
object retuned by AlertDialog.Builder.show()
method. No need to call AlertDialog.Builder.create()
.
Example:
AlertDialog dialog = alertbox.show();
if(monsterint > playerint) {
Button button = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
button.setEnabled(false);
}