Into Open Source


Using dialogs in Android

Geplaatst in Artikel door Dirk op 26/10/2010

In Android dialogs are those little popups you can sometimes see. As a developer it’s a handy thing to show messages to the user, display loading dialogs, show errors that occured,… And it’s pretty easy to implement! Although I had some problems using them, but first let’s start creating a dialog!

Creating dialogs

As I said before, creating dialogs i quite easy. One thing you need to know is that each ‘type’ of dialog you make requires an id. So let’s assume the following block of code:

    //Constants used to create dialogs
    private static final int LAODING_DIALOG = 0;
    private static final int WARNING_DIALOG = 1;
    private static final int WARNING_DIALOG_DYNAMIC = 2;

    @Override
    protected Dialog onCreateDialog(int id) {
        Dialog dialog = null;
        switch(id) {
            case LAODING_DIALOG: {
                ProgressDialog progressDialog = new ProgressDialog(this);
                progressDialog.setMessage("Laoding...");
                dialog = progressDialog;
                break;
            }
            case WARNING_DIALOG: {
                AlertDialog errorDialog = new AlertDialog.Builder(this)
                    .setMessage("An error occured!")
                    .setCancelable(false)
                    .setNeutralButton(R.string.dialogOK, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.dismiss();
                            //dismissDialog(WARNING_DIALOG) should also work!
                    }
                }).create();
                dialog = errorDialog;
                break;
            }
            case WARNING_DIALOG_DYNAMIC: {
                AlertDialog errorDialog = new AlertDialog.Builder(this)
                    .setMessage("An error occured! Time: " + new Date())
                    .setCancelable(false)
                    .setNeutralButton(R.string.dialogOK, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            removeDialog(MY_EPISODES_ERROR_DIALOG);
                        }
                    }).create();
                dialog = errorDialog;
                break;
            }
            default:
                dialog = super.onCreateDialog(id);
                break;
            }
        return dialog;
    }

This code will compile… but you won’t notice any difference in the execution of your application. We still need to start the dialogs. But before we do so we’ll first go into detail on this code snippet.
In order to be able to create dialogs you need to overwrite the ‘onCreateDialog’ method which takes exactly one parameter, id. With this parameter you identify the dialog to be shown mostly using a switch. And to keep things a bit organized the identifiers are stored on the class (or a utility class) as a integer constant.
In this sample we have three dialogs, one loading dialog with a circle spinning around while loading, next a static dialog showing the text “An error occured” and finally a dynamic dialog showing the same message as the static dialog but including the time of the creation of the dialog. The loading dialog does not have any button to close it, it will be done in code. The other two dialogs have a close button which will remove the dialog from the screen.

Working with the dialogs

As mentioned in the previous paragraph this code snippet does not yet start the dialogs. Therefore we need some code like this:

showDialog(LAODING_DIALOG);
//Do some complicated stuff that requires a loading dialog...
dismissDialog(LAODING_DIALOG);

For showing the loading dialog this should already work. But make sure for loading dialogs you start the dialog in a different thread than the thread in which you do the complicated stuff (have a look at AsyncTasks). For the other two dialogs you only need the ‘showDialog’-call as closing them should be done by the user (in the onClickListener). The code for those would look like this:

showDialog(WARNING_DIALOG);
showDialog(WARNING_DIALOG_DYNAMIC);

Dismiss or remove dialogs

As you can see in all the code samples of this article there are two options to get rid off a dialog. And both have their usages.
First you can dismiss a dialog (dissmissDialog(int id)). Dismissing a dialog will make it disappear but the activity will still keep a reference to it. So next time you want to show it, it doesn’t need to be created again, it will just popup. Removing a dialog is exactly the opposite, any reference to the dialog will be removed and next time you want show the dialog it will be re-created.

And that is the big difference. Re-create or store a reference… As you can see in the first code snippet when we want to get rid off the static warning dialog (WARNING_DIALOG) we just dismiss it. When we want to get rid off the dynamic dialog (WARNING_DIALOG_DYNAMIC) we remove it. Why the difference… Well it quite easy. If we show the dynamic dialog for the first time it will show the message ending with the current date and time (for example October 26, 2010 7:21 PM). Now if we dismiss the dialog instead of removing it and we show it a second time the text displayed will be exactly the same as the first time. Because… the dialog is not created again. If we remove the dialog and show it again the second time it will show an updated time (for example October 26, 2010 7:22 PM).
So what does this learn us? Dismissing a dialog is nothing more than just hiding the dialog. So if you have a dynamic dialog you should always get rid of it by removing it. But there’s more… Look back at the loading dialog…

The loading dialog only gets closed in code. Let’s say we have a button on the screen, if the user clicks it some data will be loaded from the internet. Before we start loading the data we’ll show the dialog, afterwards we want to get rid of the dialog. The code snippet above will perfectly do this for you. Only when you click the button the second time, the opening loading dialog will not have a spinning circle. In fact the circle is there but it’s not moving at all! That’s because you have to look at a loading dialog as dynamic dialog. So instead of dismissing the dialog we should also remove it!

showDialog(LAODING_DIALOG);
//Do some complicated stuff that requires a loading dialog...
removeDialog(LAODING_DIALOG);

Now your loading-circle will spin again!

The rules are:

  • Can the text to be displayed in a dialog be different: always remove the dialog
  • Does the dialog contains any animation (spinning wheels, loading bars,…): always remove the dialog
  • It the dialog completely static (no text that ever changes, no animated images,…): it’s safe to dismiss the dialog

Geef een reactie

Fill in your details below or click an icon to log in:

WordPress.com logo

Je reageert onder je WordPress.com account. Log Out / Bijwerken )

Twitter-afbeelding

Je reageert onder je Twitter account. Log Out / Bijwerken )

Facebook foto

Je reageert onder je Facebook account. Log Out / Bijwerken )

Verbinden met %s


Follow

Get every new post delivered to your Inbox.