Showing a Dialog

When stuff goes wrong, the user might like to know about it.

Roughly speaking, you have three major ways of informing the user of a problem from your UI… besides simply crashing:

In this chapter, we will explore that third option. If there is a problem when importing the notes, we will display an error dialog, with options to cancel or retry the import.

In Android, there are several ways to get the visual effect of a floating dialog. We will take the most modern option, which is to use a DialogFragment. As the name suggests, this is a fragment that knows how to render itself as a dialog.

The Navigation component has support for DialogFragment. There is even an option to get a result from that dialog, such as whether the user opted to retry or cancel the import. We will leverage that as part of our work here.

This is a continuation of the work we did in the previous tutorial. The book’s GitLab repository contains the results of the previous tutorial as well as the results of completing the work in this tutorial.

Step #1: Adding a Stub Fragment

We need another fragment!

Rather than being tied to a specific piece of business logic, like displaying a to-do item, this error fragment can be more “general purpose”. Plus, for our limited needs, we can skip giving it a viewmodel. So, we can just place it in the ui sub-package rather than create a brand-new package for it.

Right-click over the com.commonsware.todo.ui package in the java/ directory and choose “New” > “Kotlin File/Class” from the context menu. For the name, fill in ErrorDialogFragment, and choose “Class” for the kind. Press Enter or Return to create the class. Then, replace the class declaration with:

package com.commonsware.todo.ui

import androidx.fragment.app.DialogFragment

class ErrorDialogFragment : DialogFragment() {
}

enum class ErrorScenario { Import, None }

Unlike our other fragments, we inherit from DialogFragment this time. Otherwise, this stub is pretty much like the stubs of the other fragments that we created several chapters ago.

We also define an ErrorScenario. This is another enum, akin to the FilterMode that we created earlier. We will use this to allow users of ErrorDialogFragment to indicate what “scenario” the error is about. This will be important for fragments that might show multiple error dialogs and need to distinguish one from another for handling “retry” requests. Import represents an error in importing data, while None means that there is no current error.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.