How to create a confirmation dialog in Java ME
This example shows how to create a confirmation dialog in Java ME by using standard LCDUI Alert class. This dialog could be used for example for confirming closing of a MIDlet.
Article Metadata
Source code
The full source code for a test MIDlet:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class ConfirmationMIDlet extends MIDlet implements CommandListener {
private Form form;
private Alert alert;
private Command exitCommand;
public void startApp() {
form = new Form("ConfirmationMIDlet");
exitCommand = new Command("Exit", Command.EXIT, 1);
form.setCommandListener(this);
form.addCommand(exitCommand);
Display.getDisplay(this).setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction (Command c, Displayable d) {
if (c == exitCommand) {
showConfirmation("Confirmation", "Do you really want to exit?");
}
}
private void closeAlert() {
Display.getDisplay(this).setCurrent(form);
alert = null;
}
protected void showConfirmation(String title, String text) {
alert = new Alert(title, text, null, AlertType.CONFIRMATION);
alert.addCommand(new Command ("Yes", Command.OK, 1));
alert.addCommand(new Command("No", Command.CANCEL, 1));
alert.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
if (c.getLabel().equals("Yes")) {
notifyDestroyed();
}
if (c.getLabel().equals("No")) {
closeAlert();
}
}
});
Display.getDisplay(this).setCurrent(alert, form);
}
}


12 Sep
2009
This brief article demonstrates the use of confirmation dialogs in Java ME. The use of confirmation prompts requiring the user to confirm a system action is a common phenomenen in Java ME MIDlets. The article provides a code example demonstrating the use of the Alert class in Java ME as a confirmation dialog.
The code example shows how to add commands to an Alert to handle user input. The use of the commandAction class shows how user input is processed.
17 Sep
2009
In java script, there is a function like alert("").and it shows a confirmation dialog box with a button(e.g.,OK.).Same here in mobile development.This article has a function showConfirmation(), it has two arguments title and text. Title is for dialog box and text is the message for that dialog box.
Good use of alert class. It has a method addCommand and is used for adding a commands to a dialog box. This all important information with coding is useful in every mobile application.