Results 1 to 3 of 3
  1. #1
    Java Tutorial is offline Member
    Join Date
    Nov 2007
    Rep Power

    Default MIDlet programming

    MIDlets are an important part of J2ME technology. A MIDlet is simply a Java class with special features. To execute a MIDlet on a device, the target device should implement Java ME, CLDC and MIDP to run. MIDlets posses "compile once, run anywhere" feature which makes them very portable. MIDlet are distributes using jar and jad files file.

    A MIDlet class whould have the following:

    - The main class should extend javax.microedition.midlet.MIDlet.
    - The MIDlet class should be packed into a JAR file for deployment.
    - The .jar file needs to be pre-verified by using a preverifier.
    - Sometimes it is important to sign the JAR file by the mobile phone's carrier.

    MIDlet Lifecycle

    A MIDlet has 4 different states: loaded, active, paused, and destroyed.

    MIDlet programming-lifecycle.jpg

    Loaded: A MIDlet is said to be in loaded state, when it is loaded into the device and the constructor is called. This is done a bit before when the AMS (Application Management Software) starts the application by calling the startApp() method.

    Active: startApp() method is called to bring the MIDlet in active state. A MIDlet remains in the active state unless the AMS calls pauseApp() or destroyApp().

    Paused: AMS calls pauseApp() method to pauses the MIDlet.

    Destroyed: AMS calls desroyApp() method to terminate the MIDlet. Doing so will release all the resources occupied by the MIDlet.

    Note: State is only changed when a method returns. So the change callback method should terminate quickly.

    Review the method signatures in the given MIDlet. I will present more meaningful examples later.

    Java Code:
    import javax.microedition.midlet.*;
    public class HelloMIDlet
        extends MIDlet 
      public HelloMIDlet() {
      public void startApp() {
      public void pauseApp() {}
      public void destroyApp(boolean unconditional) {}
    MIDlet suite

    MIDlet suite is very much like a standard Java project in Eclipse. Please note that it’s not a requirement to place MIDlets inside a Java Archive (JAR) file, but JAR files provide the most common means of distributing MIDP applications. The MIDlet Suite comproses of all files and resources that may be required as part of a MIDlet. The MIDlet Suite consists of

    - Java class files enclosed in a JAR file
    - manifest file describing the contents of the JAR
    - resources (images, etc) enclosed in a JAR file
    - Java Application Descriptor file (JAD)

    Sun Java Toolkit

    You may develop MIDlets using Sun Java Wireless Toolkit. For that first install J2SE 5.0 and then install Sun Java Wireless Toolkit. You may download the toolkit from:
    Sun Java Wireless Toolkit for CLDC (formerly known as Java 2 Platform, Micro Edition (J2ME) Wireless Toolkit).

    The toolkit will help us in building the source code and to run it on the emulator. It does not provide development environment. We will be writing MIDlets in text editors.

    IDEs for MIDlet development

    You need an environment for MIDlet development. You may use JBuilder, Eclipse or NetBEans with appropriate plugins installed. You will get an emulator for testing your MIDlets which is very handy. A standard mobile emulator is shown below:

    MIDlet programming-emulator.jpg

    MIDlet deployment – JAR files

    MIDlet deployment is very interesting because one would like to see the MIDlet running on the target device. It is just a matter of knowing how this works.

    Once you code a MIDlet, you have to build and test it on emulator. When all the tests are passed, you would like to finally deploy it to your mobile device to see how it works in real world scnerio.

    There are actually two ways to deploy MIDlets.
    - transferring JAR through dada cable
    - transferring JAR through web

    For testing, the first method is OK but it cannot be used for mass distribution, since you cannot even think of transferring JARs to hundreds and thousands of mobile phones.

    We will transfer the JARs through a PC to the phone. There are few options to do this:

    - Explicit physical connection via USB cable
    - Direct InfraRed (IR) connection
    - Direct Bluetooth connection

    which option to choose, depends on the cell phone you have. We will need a USB cable for the first option, which is provided by your phone manufacturer and also there will be a software from the manufacturer. Do read the manual before opting this.

    You may also use InfraRed and Bluetooth options as well. If your phone and your PC both have InfraRed, then you can transfer files via InfraRed. This is very useful option if you are suing Windows XP.

    MIDlet deployment - JAD files

    JAD (Java Application Decription files) contains the JAR file name and size attributes. From mobile phone, you will make an HTTP request for the JAR file. In response, you will get the JAD file on to your mobile device. Mobile device have AMS (Application Management System) that will read the required attributes and will make another HTTP request to the server for the required JAR file. In response, you will get the JAR file on to your mobile device which actually is the MIDlet.

    An example JAD file is given below:

    Java Code:
    MIDlet-Name: Show Properties MIDlet
    MIDlet-Version: 1.0.1
    MIDlet-Vendor: My Corporation Inc.
    MIDlet-Jar-URL: file://showProperties.jar
    MIDlet-Jar-Size: 1132
    MIDlet-1: ShowProps, , showProperties
    JadFile-Version: 1.5
    MIDlet-Data-Size: 500
    MIDP high level APIs

    We use MIDP high level APIs for creating GUI components. I will present some very important high level APIs.


    MIDlets can be used for processing only which means no GUI required. But mostly, you would like the users to interact with your MIDlet. In such case, you need to get the display working. This is done by obtaining an instance of the Display class. For that, call Display.getDisplay (MIDlet midlet), where the MIDlet itself is given as parameter.

    The classes related to user interfaces are located in javax.microedition.lcdui. So, import it for use. There is a setCurrent() method of Display class which is used to set the current display content of the MIDlet. The setCurrent() method notifies the AMS that the MIDlet would like to have the given Displayable object displayed. There is a slight difference between Display and Displayable. The Display class represents the display hardware, whereas Displayable is something that can be shown on the display.

    Java Code:
    Display display;
    Form mainForm;
    public HelloMidp () {
        mainForm = new Form ("HelloMidp");
    public void startApp() {
        display = Displayable.getDisplay (this);
        display.setCurrent (mainForm);

    Let talks about Screen class. It is an abstract class but has some functionalities. Each Screen can have two characteristics which are title and ticker. The title is a String that appears above the screen contents and the ticker is a graphical component that appears above the title. This ticker can be used to scroll information across to the user. Please note that both of these characteristics are optional. The following figure shows titles and tickers on a screen.

    MIDlet programming-screen.gif

    The methods shown below are used to set and retrieve the title and the ticker, respectively.

    Java Code:
    public void setTitle(String title);
    public String getTitle(  );
    public void setTicker(Ticker ticker);
    public Ticker getTicker(  );

    A ticker can be attached to Alert, TextBox, List, and Form. We use the Ticker constructor to create a Ticker.

    Java Code:
    public Ticker(String str);
    To play the ticker string, use following methods:

    Java Code:
    public String getString(  );
    public void setString(String s);
    After creating a ticket, it is attached to a screen using screen’s setTicker( ) method. Time for an example: The given example creates a List screen and attaches a ticker to it:

    Java Code:
    Display display = Display.getDisplay(  );
    List list = new List("Languages", Choice.EXCLUSIVE);
    list.append("English", null);
    list.append("Arabic", null);
    list.setTicker(new Ticker("Welcome to shop"));

    We use TextBox object to allow user to enter and edit text. It is similar to textboxes we see daily on the web. We may use TextBox in MIDlets to get name, a phone number, an email address, or a password etc from the user. One needs to provide 4 parameters while creating a TextBox. The constructor reads like:

    Java Code:
    public TextBox(String title, String text, int maxSize, int constraints);
    Lets talk about each parameter. The title is simply the screen title. The text and maxSize are for the default text that will appear in the TextBox. The last parameter is used to limit the user's input. The available constraints are as follows:

    Java Code:
    TextField.ANY // The user is allowed to enter any character.
    TextField.EMAILADDR // Input must be an email address.
    TextField.NUMBER // Input must be an integer value.
    TextField.PASSWD //The text entered will be 
    //masked (replaced by asterisks), so the characters typed are not visible.
    TextField.PHONENUMBER // Input must be a phone number.
    TextField.URL // Input must be a URL.
    For example:

    Java Code:
    TextBox t = new TextBox("Tel", "", 12, TextField.PHONENUMBER | TextField.PASSWD);
    Designing MIDlet GUI – An Example

    Now let me present a meaningful example.
    Firstly, importing the required packages

    Java Code:
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    Now lets declare the class (GuiTests) and define the components we need. In this example, we will use Display, List, TextBox, Ticker, Alert, DateField, Form, Gauge and Commands.

    Java Code:
    public class GuiTests extends MIDlet 
    implements CommandListener {
        // display manager
        Display display;
        List menu;
        List choose;
        TextBox input;
        Ticker ticker = new Ticker(
        "Test GUI Components");
        final Alert soundAlert = 
        new Alert("sound Alert");
        DateField date = new DateField("Today's date: ", DateField.DATE);
        Form form = new Form("Form for Stuff");
        Form today = new Form("Today's date");
        Gauge gauge = new Gauge("Progress Bar", false, 20, 9);
        TextField textfield = new TextField(
        "TextField Label", "abc", 50, 0);
        // commands
        static final Command backCommand =
         new Command("Back", Command.BACK, 0);
        static final Command mainMenuCommand =
        new Command("Main", Command.SCREEN, 1);
        static final Command exitCommand =
         new Command("Exit", Command.STOP, 2);
        String currentMenu;
        // constructor.
        public GuiTests() {
    Now lets start the MIDlet by creating a list of items and associating the exit command with it.

    Java Code:
        public void startApp() throws 
        MIDletStateChangeException {
          display = Display.getDisplay(this);
          menu = new List(
          "Test Components", Choice.IMPLICIT);
          menu.append("Test TextBox", null);
          menu.append("Test List", null);
          menu.append("Test Alert", null);
          menu.append("Test Date", null);
          menu.append("Test Form", null);
          // form
          // today
    pauseApp and destroyApp methods should be there in a MIDlet. So lets define these.

    Java Code:
        public void pauseApp() {
          display = null;
          choose = null;
          menu = null;
          ticker = null;
          form = null;
          today = null;
          input = null;
          gauge = null;
          textfield = null;      
        public void destroyApp(boolean unconditional) {
    Now lets write the methods to test the GUI.

    Java Code:
        // main menu
        void mainMenu() {
          currentMenu = "Main";
         * Test the TextBox component.
        public void testTextBox() {
          input = new TextBox
          ("Enter Some Text:", "", 10, TextField.ANY);
          input.setTicker(new Ticker(
          "Testing TextBox"));
          currentMenu = "input";
         * Test the List component.
        public void testList() {
            choose = new List("Choose Items",
            choose.setTicker(new Ticker(
            "Testing List"));
            choose.append("Item 1", null);
            choose.append("Item 2", null);
            choose.append("Item 3", null);
            currentMenu = "list"; 
        * Test the Alert component.
       public void testAlert() {
          soundAlert.setString("** ERROR **");
        * Test the DateField component.
       public void testDate() {
          java.util.Date now = new java.util.Date();
          currentMenu = "date";
        * Test the Form component.
       public void testForm() {
          currentMenu = "form";
        * Handle events.
       public void commandAction(Command c,
       Displayable d) {
          String label = c.getLabel();
          if (label.equals("Exit")) {
          } else if (label.equals("Back")) {
              || currentMenu.equals("input") ||
                   || currentMenu.equals("form")) {
                // go back to menu
          } else {
             List down = (List)display.getCurrent();
             switch(down.getSelectedIndex()) {
               case 0: testTextBox();break;
               case 1: testList();break;
               case 2: testAlert();break;
               case 3: testDate();break;
               case 4: testForm();break;
    Try this example at your end. It’s a good starting point.

    MIDP Low-Level API

    The MIDP low-level APIs provides little abstraction. They are for applications that need precise placement and control of graphic elements and access to low-level input events. This API gives the application full control over what is being drawn on the display. Examples of classes that implement the low-level API are Canvas and Graphics.


    MIDlet programming is very easy and fun. If you are using an IDE for development, then you will really enjoy the development, since the emulator is built in.

    MIDLet user interface components are different from AWT and Swing components. They are light weight and simple. Programming these components is very easy as compared with the AWT and Swing libraries.

  2. #2
    cheeryTomato is offline Member
    Join Date
    Aug 2007
    Rep Power

    Lightbulb Is my code correct?

    The following codes doesn't work for me:
    display = Displayable.getDisplay (this);

    It will only work when I changed into this code:
    display = Display.getDisplay (this);

    As for the Ticker example, it will only work for me when I implement 'this' into Display.getDisplay:
    Display display = Display.getDisplay(this);

  3. #3
    ezrak is offline Member
    Join Date
    Oct 2008
    Rep Power

    Default help

    i have created a midlet that displays a menu. When the yes button is clicked it then validates the user then follows the option that was selected, the problem is that after the selection is made,the user canot go back to the menu. pliz help me out

Similar Threads

  1. sms midlet
    By Poonam in forum CLDC and MIDP
    Replies: 3
    Last Post: 11-25-2009, 02:47 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts