cyroxx
cyroxx

Reputation: 3877

How to display a (modal) dialog at the very start of the app?

At the start of my Android app the user is required to choose from a list of alternatives. Here is why.

Let's assume I have a long list of items, and each item belongs to exactly one category. Each user is only interested in one specific category. Thus, when the app is started and the SharedPreferences don't contain any information about the selected category, a modal dialog should be displayed - here the user has to choose his or her category of interest. After having selected a category, only the items of that category are displayed.

So far, I tried to implement this behavior in the Activity's onCreate() method, which doesn't work obviously. The dialog is not shown or at least not long enough so that I could see it.

To be honest, I didn't expect the code to work by calling it from onCreate(). However, I was unable to find a suitable event handler in the Activity from where I could trigger the dialog.

Where should this dialog be triggered from in order to ensure the selection of a category (before any other data is loaded)?

Thanks in advance.

Here's the code:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    setContentView(R.layout.activity_item_list);
    ...
    ensureCategorySelected();
}

where the relevant method is

private void ensureCategorySelected() {
    String chosenCategory = getCategoryFromSharedPreferences();

    if (chosenCategory != null) {
        final CharSequence[] items = getCategories();

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Choose category");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                // handle the selection of the category
            }
        });
        AlertDialog alert = builder.show();
    }
}

Upvotes: 0

Views: 1352

Answers (1)

ixx
ixx

Reputation: 32273

You have a logic problem there. You want to show the dialog when there are still no preferences saved, and you are showing it when there are preferences saved. Change it to chosenCategory == null and it should work.

And why didn't you expect the code to work in onCreate()? I don't see a problem opening a dialog there.

Edit: I'm not quite sure if onCreate() is the correct place to show the dialog. Try putting ensureCategorySelected() in onStart() instead of onCreate().

You could also consider implementing an activity for this, which you could start with startActivityForResult().

Upvotes: 2

Related Questions