Further Java ME


General operation of a Java ME application

Java ME applications typically consist of several screens, which you navigate between through the use of commands. met in EWT). For instance:

A typical Java ME application will include a commandAction() method which reacts differently depending on the type of Command the user selected and the current item displayed on the screen. For instance, in the login application from last week, the OK command brings up the password text box if the currently-displayed item is the username box, but it validates the username and password if the currently-displayed item is the password box.

Displayables - objects that can fill the screen

A number of different types of user interface element can fill the screen in a Java ME application. These include the TextBox and the Alert, which you have already met, and also a number of others you haven't met including the List (discussed below). All user interface elements which can fill up the whole screen are Displayable objects: they extend from the Java ME Displayable class.

Lists

The most important user interface element in a Java ME application is probably the list. A list represents a selectable choice of items: essentially, a menu. A List is a Displayable - that is, it can fill the whole phone screen. So how do you create a list in Java ME?

Reacting to events from the list

We need to add code to react to the list in our commandAction method. Remember the form of the commandAction method:

public void commandAction(Command c,Displayable s)
The first parameter, Command c represents the Command which generated this event. This would normally be one of our Command objects such as our ok or quit commands. However when a List item is selected, the Command sent is an inbuilt Command called List.SELECT_COMMAND. So to test for the list item being selected, you would use code such as this:
public void commandAction(Command c, Displayable s)
{
    if (c==List.SELECT_COMMAND)
    {
        // act upon a list item being selected 
    }
    else if (c.getCommandType()==Command.OK)
    {
        // act upon OK being selected
    }
    else if (c.getCommandType()==Command.EXIT)
    {
        // act upon Exit being selected
    }
}

Retrieving the selected item from the list

Retrieving the item the user selected from the list is easy. All you need to do is call getSelectedIndex on the List object that produced the command. Here is a code example:

public void commandAction(Command c, Displayable s)
{
    if(c==List.SELECT_COMMAND)
    {
        // Get the List which produced the Command
        List list = (List)s;
        System.out.println("You selected list option number : " + 
                                list.getSelectedIndex());
    }
}
Note how we have to cast the Displayable s to List to be able to treat it as a List.

Forms

Often we want to collect several user interface items on one screen. We do this with a Form. a Form is a Displayable (i.e. an object capable of occupying the main display of the screen) which can hold other objects.

A typical object that you might want to add to a Form is a TextField. A TextField is similar to a TextBox, but it does not occupy the whole screen, but just one line on a Form: it is equivalent to a JTextField in Swing or an ordinary input box in HTML. Here is an example of an application which creates two TextFields and adds them to a Form. The commands are attached to the Form (commands are always attached to Displayables, i.e. objects that occupy the whole screen) and the commandAction() method reads and validates the username and password entered in the two TextFields.

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class Project4 extends MIDlet implements CommandListener
{


    Form form;
    TextField username, password;

    // Stage 2 - add two Commands
    Command ok, exit;

    // Constructor for the class
    public Project4()
    {
        username = new TextField("Username","",50,TextField.ANY);
        password = new TextField("Password","",50,TextField.PASSWORD);
        

        // Create a form: "Login" is its title
        form = new Form("Login");
        form.append(username);
        form.append(password);

        exit = new Command("Exit",Command.EXIT,1);
        ok = new Command("Enter",Command.OK,1);
        
        // Associate the commands with the form, i.e. make the form 
        //respond to commands
        form.addCommand(ok);
        form.addCommand(exit);
    }

    // These are abstract so have to be overridden

    public void startApp()
    {
        Display display = Display.getDisplay(this);
        display.setCurrent(form);

        form.setCommandListener(this);
    }
    

    // Midlets must have this even if blank - code to handle pausing the a
    // application
    public void pauseApp()
    {
        
    }
    
    
    // Likewise midlets must have this even if blank - code to handle 
    // destroying the application
    public void destroyApp(boolean unconditional)
    {
    }    

    // Stage 2 - commandAction is the code to respond to commands
    public void commandAction(Command c, Displayable s)
    {
        // What command type is it?
        switch(c.getCommandType())
        {
            // if an exit command, quit the app
            case Command.EXIT: notifyDestroyed(); break;

            // if an OK command....
            case Command.OK: 
                String msg;
                if(s == form)
                {
                    if(username.getString().equals("michelle") &&
                       password.getString().equals("wtk123"))
                    {
                        msg="Correct!";
                    }
                    else
                    {
                        msg="Incorrect!";
                    }
                    Alert a = new Alert(msg,msg,null,AlertType.INFO);
                    Display.getDisplay(this).setCurrent(a);
                }
                break;
        }
    }
}

Note how the commandAction reads in what the user entered in the two text fields and validates the correct username and password.

Radio buttons

Another useful user interface element is the set of radio buttons, i.e. a group of selectable options where you can only select one of the set of options. There are actually two ways in which you can create radio buttons in Java ME:

Here is an example of radio buttons as a ChoiceGroup. The user has to select their favourite programming language. Note how we create an array of Strings, representing the individual choices, and pass them into the ChoiceGroup in the constructor. Note also how we use getSelectedIndex() once again to get the index of the radio button that the user selected, and then use the index to look up the corresponding language in the array of languages to work out which language the user selected.

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class Project4 extends MIDlet implements CommandListener
{


    Form form;
    TextField username, password;
    ChoiceGroup choices;
    String[] languages =  { "Java", "PHP", "C++" }; 

    // Stage 2 - add two Commands
    Command ok, exit;

    // Constructor for the class
    public Project4()
    {
        form = new Form("Select favourite language");

        choices=new ChoiceGroup("Favourite programming language?",
            Choice.EXCLUSIVE,languages,null);        
        form.append(choices);

        /* Project4: Set up two commands. The first parameter will be the text 
        of the command, the second
        will be the command type. */
        exit = new Command("Exit",Command.EXIT,1);
        ok = new Command("Enter",Command.OK,2);
        
        // Associate the commands with the textbox, i.e. make the textbox 
        //respond to commands
        form.addCommand(ok);
        form.addCommand(exit);
    }

    public void startApp()
    {
        Display display = Display.getDisplay(this);
        display.setCurrent(form);

        form.setCommandListener(this);
    }
    

    // Midlets must have this even if blank - code to handle pausing the a
    // application
    public void pauseApp()
    {
        
    }
    
    
    // Likewise midlets must have this even if blank - code to handle 
    // destroying the application
    public void destroyApp(boolean unconditional)
    {
    }    

    // Stage 2 - commandAction is the code to respond to commands
    public void commandAction(Command c, Displayable s)
    {
        // What command type is it?
        switch(c.getCommandType())
        {
            // if an exit command, quit the app
            case Command.EXIT: notifyDestroyed(); break;

            // if an OK command....
            case Command.OK: 
                String msg;
                if(s == form)
                {
                    msg="Your favourite language is " +
                            languages[choices.getSelectedIndex()];
                    Alert a = new Alert("Favourite language",
                            msg,null,AlertType.INFO);
                    Display.getDisplay(this).setCurrent(a);
                }
                break;
        }
    }
}

Exercises

Make sure you complete the EWT exercises from last week, here first!

  1. Write a pizza ordering application. Create a form with two fields, one for name and one for address. Add OK and Quit actions to the form.
  2. In a new application, use a List to store the pizza flavours and make it the main Displayable of the application. When the user selects a flavour, display the flavour and price in an Alert. (There is no need to read the name and address)

Further exercises

If you finish all the above, read the MSAA notes. These are notes from another unit dedicated to mobile development; if you are not doing the MSAA unit you might want to start here to find out more things you can do with Java ME.