How to add commands to Alert in J2ME

Today I am going to write a simple application after those series of PhoneBook applications 🙂 In this post you will be able to get to know how to add commands to an Alert. Other than that I have included the way of declaring an Exception in Java. First let’s see the advantages of adding commands to Alerts.

Just think about my previous mobile app that is PhoneBook. There when you select a contact and press the Delete command, it get deleted without any warning message. But may be you have press that key accidentally. Such a case, as developers, we need to warn the user that he is going to perform a critical application and what are the consequences that he is going to face after that action performed. There we need Alerts with commands. Then if the user is not sure about what he/she going to do, can be cancel the process. You can clearly understand what I am describing by looking at the following images.

Figure 1

If I describe about the Figure 1, there I have included two Item types. They are ChoiceGroup and DateField. The command Delete activate only when you have selected ChoiceGroup item. When you select an element from the ChoiceGroup and press on the Delete command you will get an Alert message as shown in the Figure 2.

Alert 2
Figure 2

Here you can continue the action by pressing OK command or cancel the process by clicking Cancel command. If you press Cancel command you will be redirect to the previous interface without performing the delete process. But if you press the OK command you will again redirect to the first interface after completing the delete process.

In this code sample I have included the following class newly because as I have mentioned earlier I declared an Exception.

  • IndexOutOfBoundsException

But in this code sample I didn’t use “throw” part which we use in actual throwing part of the exception. Let’s see the code sample before it’s getting boring 😉

package anuja;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.DateField;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemCommandListener;
import javax.microedition.midlet.MIDlet;

 * @author Anuja
public class AlertFun extends MIDlet implements ItemCommandListener, CommandListener {

    private Display dispaly;
    private Form messageForm;
    private ChoiceGroup msgChoGrp;
    private DateField dateFld;
    private Command delCmd;
    private Alert warningAlert;
    private Command okCmd;
    private Command cancelCmd;
    private int getSelInd;
    private Command exitCmd;

    public void startApp() {
        dispaly = Display.getDisplay(this);

        msgChoGrp = new ChoiceGroup("", Choice.EXCLUSIVE);
        msgChoGrp.append("First", null);
        msgChoGrp.append("Second", null);

        dateFld = new DateField("Date", DateField.DATE);
        Item[] items = new Item[]{msgChoGrp, dateFld};
        messageForm = new Form("Messages", items);

        // Adding a command to ChoiceGroup item and call setItemCommandListener()
        delCmd = new Command("Delete", Command.OK, 4);

        // Adding a command to Form and call setCommandListener()
        exitCmd = new Command("Exit", Command.EXIT, 7);


    public void pauseApp() {

    public void destroyApp(boolean unconditional) {

    public void commandAction(Command c, Item item) {
        if (c == delCmd) {

            // Getting selected index from the ChoiceGroup
            getSelInd = msgChoGrp.getSelectedIndex();

            warningAlert = new Alert("Permanently Delete?", "You cannot undone this !!!", null, AlertType.CONFIRMATION);

            okCmd = new Command("OK", Command.OK, 4);
            cancelCmd = new Command("Cancel", Command.CANCEL, 3);

            dispaly.setCurrent(warningAlert, messageForm);


    // throws keyword represents the declaaration part of an exception
    // Generally, throws keyword used with a method or a constructor
    public void commandAction(Command c, Displayable d) throws IndexOutOfBoundsException {
        if (c == okCmd) {
            try {
            }catch(IndexOutOfBoundsException ioobe){
                System.out.println("There is nothing to delete. " + ioobe.toString());
        } else if (c == cancelCmd) {
        }else if(c == exitCmd){

Another thing I would like to emphasis here. There are only eight item types act as direct sub classes of the Item class. Those are ChoiceGroup, CustomItem, DateField, Gauge, ImageItem, Spacer, StringItem and TextField. So if we adding a command to those items, we need to call setItemCommandListner not the setCommandlistner as we normally use with the Form.

That’s all for today. Have a nice day 🙂


About AnujAroshA

Working as a Senior Software Engineer. Specialized in iOS application development. A simple person :)
This entry was posted in J2ME examples. Bookmark the permalink.

One Response to How to add commands to Alert in J2ME

  1. snowy says:

    do you know how to code for dictionary application for touch screen mobiles???
    yours work is appreciable:)

Leave a Reply

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

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s