aarelovich
aarelovich

Reputation: 5566

Android dialog disappears on its own

I'm using the following code to create my own dialog:

public void ShowMessageDialog(String str){
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(str);
    builder.setCancelable(false);
    builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {          
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    AlertDialog alert = builder.create();
    alert.show();
}

It works fine but it appears the Dialog disappears on it's own when used inside this function:

public void test(String str){
    ShowMessageDialog("About to start new activity");
    Intent intent = new Intent(this,PageViewer.class);
    startActivity(intent);
}

It seems that the new activity is created and obviously gets rid of the dialog. But why? Shouldn't the activity stop before opening the new one?

Thanks!

Upvotes: 6

Views: 7485

Answers (1)

user468311
user468311

Reputation:

Intent which is about to fire doesn't wait for your dialog to be canceled. So, right after dialog is shown, new Activity is started. You could accomplish what you want like this:

public void ShowMessageDialog(String str){
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(str);
    builder.setCancelable(false);
    builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {          
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
            Intent intent = new Intent(this,PageViewer.class);
            startActivity(intent);
        }
    });
    AlertDialog alert = builder.create();
    alert.show();
}

public void test(String str){
    ShowMessageDialog("About to start new activity");
}

Upvotes: 7

Related Questions