Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Can not change the text appears in AlertDialog

I created an AlertDialog to show the user next level challenges when one is succeeded. So, the corresponding code is like this. when the game is succeeded showDialog(R.id.display_success) is called and the following code is executed.

So, I am expecting to execute this code in every call. However; the game is executing only once and showing the same AlertDialog in every other execution. I mean, like the instance is not created after the first one is created and the first instance is used all the time.

case R.id.display_success:           
       updateGameSettings();
       message = formatLevel()
       + formatMission();
       return new AlertDialog.Builder(this)
       .setIcon(R.drawable.smiley_happy)
       .setTitle(R.string.dialog_success)
       .setMessage(message)
       .setPositiveButton(R.string.alert_dialog_newgame, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog,     int whichButton) {
                       startANewGame();
               }
       })
       .setNegativeButton(R.string.exit, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int whichButton) {
                     finish();
               }
       })
       .create();
like image 318
Ömer Avatar asked May 07 '09 11:05

Ömer


2 Answers

I think I have a fix for the inconsistent behavior of onPrepareDialog. When initially creating the dialog (when it's still an AlertDialog.Builder), you have to set the message to an initial state (not null) or onPrepareDialog will NOT overwrite the message with the intended value. So when you're creating the dialog, do something like this to always have a non-null value in the message. I struggled with this for days and found this solution by accident:

AlertDialog.Builder resultAlert = new AlertDialog.Builder(context);

if ( message == null ) {
    resultAlert.setMessage("");
} else {
    resultAlert.setMessage(message);
}
like image 196
Jerry Destremps Avatar answered Oct 29 '22 19:10

Jerry Destremps


onPrepareDialog method is called when the dialog is shown. So, it is better to change the text or other features by overriding this method.

like image 33
Ömer Avatar answered Oct 29 '22 19:10

Ömer