How To Show An Alert Dialog In Android
An alert dialog is a compact window that appears above an Android screen to request attention or offer a short decision. It can display a title, message, buttons, and optional controls such as a text field, checkbox, or list. For beginners, it is one of the clearest ways to learn how Android event handling works.
A dialog is useful when an action needs confirmation before it continues. A shopping app might confirm an order in Australian dollars, a transport app could ask before removing a saved Opal or Myki trip, and a settings screen may warn users before clearing stored information. The message should explain the action clearly rather than interrupting users without context.
This tutorial uses Java with AndroidX and the standard AlertDialog.Builder class. The same approach works in Android Studio projects that use an AppCompatActivity. AndroidX provides a consistent appearance across devices, including phones commonly used in Sydney, Melbourne, Brisbane, and regional areas.
The examples can be adapted for a simple Android application, a SQLite-backed project, or a form that collects user input. Each example focuses on a small, reusable pattern so that the dialog behaviour remains easy to test and maintain.
Create A Basic Alert Dialog
Start by adding a button to an activity layout. The button can use any suitable label, such as “Show Message”, and its click event will create the dialog. The following Java code displays a title, explanatory text, and a single dismissal button:
Button showDialogButton = findViewById(R.id.show_dialog_button);
showDialogButton.setOnClickListener(view -> {
new AlertDialog.Builder(MainActivity.this)
.setTitle("Welcome")
.setMessage("Your account is ready to use.")
.setPositiveButton("OK", (dialog, which) -> dialog.dismiss())
.show();
});
setTitle() adds the heading, while setMessage() supplies the main content. Calling show() is essential because building the dialog does not display it by itself. The positive button closes the window by default, so explicitly calling dismiss() is optional in this simple example.
Keep the message short enough to scan on a small screen. A lengthy paragraph can be difficult to read on an older handset or while someone is using a phone on a busy Sydney train platform.
Add Positive And Negative Actions
Confirmation dialogs generally need two choices. For example, an application that deletes a saved item should explain what will happen and provide an obvious way to cancel. Use setPositiveButton() for the action that proceeds and setNegativeButton() for the safer alternative:
new AlertDialog.Builder(MainActivity.this)
.setTitle("Delete saved address?")
.setMessage("This address will be removed from your local list.")
.setPositiveButton("Delete", (dialog, which) -> {
deleteSavedAddress();
})
.setNegativeButton("Cancel", (dialog, which) -> {
dialog.dismiss();
})
.show();
The order of buttons is managed by Android and the selected theme, so avoid describing their screen position in your instructions. Give the destructive action a precise label such as “Delete” instead of a vague word like “Continue”. This helps users make an informed choice when managing delivery details or other data for the Australian market.
For high-impact actions, the dialog should explain whether information can be recovered. A cancellation button should leave the underlying activity unchanged. If the user taps outside the dialog or presses the Back button, Android may also dismiss it unless that behaviour is disabled.
Control Dismissal And Handle Results
Some alerts should remain visible until the user makes an explicit choice. This is useful when the message contains an important permission explanation or a required acknowledgement. Call setCancelable(false) to prevent dismissal by tapping outside the window or pressing Back:
new AlertDialog.Builder(MainActivity.this)
.setTitle("Terms update")
.setMessage("Please review the updated conditions before continuing.")
.setCancelable(false)
.setPositiveButton("Accept", (dialog, which) -> {
openHomeScreen();
})
.show();
Use this setting carefully. Blocking dismissal for an unimportant notification makes an app feel frustrating, particularly when a user is on a limited mobile connection in regional Queensland or Western Australia. A cancellable dialog is usually the better choice for informational content.
The button listener is where the application responds to the decision. It might save a preference, navigate to another activity, refresh a list, or start a network request. Keep long operations out of the listener itself; call a separate method so the activity remains readable and the behaviour can be tested independently.
Display A Choice List Or Text Field
An alert can present a list of options instead of ordinary buttons. This is convenient for a small set of mutually exclusive choices, such as selecting a delivery suburb, notification frequency, or preferred payment method. A single-choice list records the selected position:
String[] frequencies = {"Daily", "Weekly", "Monthly"};
new AlertDialog.Builder(MainActivity.this)
.setTitle("Notification frequency")
.setSingleChoiceItems(frequencies, 1, (dialog, which) -> {
saveFrequency(frequencies[which]);
dialog.dismiss();
})
.setNegativeButton("Cancel", null)
.show();
For multiple independent options, use setMultiChoiceItems(). The callback provides the item position and a Boolean value indicating whether that item is selected. Avoid placing too many choices in a dialog; a dedicated screen, spinner, or RecyclerView is usually easier to use when the list grows.
Text entry is another common pattern. Create an EditText, add it to the builder, and read its value when the positive button is pressed:
EditText input = new EditText(MainActivity.this);
input.setHint("Enter a label");
new AlertDialog.Builder(MainActivity.this)
.setTitle("Name this location")
.setView(input)
.setPositiveButton("Save", (dialog, which) -> {
String label = input.getText().toString().trim();
saveLocationLabel(label);
})
.setNegativeButton("Cancel", null)
.show();
Validate empty input before saving it. For a production app, set an appropriate input type, provide a useful label, and consider how the soft keyboard affects the layout on smaller devices.
Connect Dialogs With Stored App Data
Dialogs become more useful when their decisions affect persistent data. A confirmation button could remove a row from a local database, while a text-entry dialog could add a user-defined category. If your project stores information with SQLite, the SQLiteOpenHelper database guide explains how to create and manage the underlying database.
A typical delete flow asks for confirmation first, then performs the database operation only inside the positive-button listener:
.setPositiveButton("Remove", (dialog, which) -> {
SQLiteDatabase database = dbHelper.getWritableDatabase();
database.delete("places", "id = ?", new String[]{String.valueOf(placeId)});
refreshPlaces();
})
Use parameterised selection arguments, as shown above, rather than joining raw values into SQL strings. After changing the data, refresh the visible ListView or RecyclerView so the interface matches the database. This separation makes it easier to support later changes, such as synchronising records with a server or handling intermittent connectivity.
Before release, test the dialog in portrait and landscape modes, with large text enabled, and using TalkBack. Verify that button labels are understandable, that important content is not clipped, and that the workflow follows relevant Australian privacy expectations when personal information is deleted or retained. A focused alert is a small component, but careful wording and reliable actions make the whole application feel trustworthy.