Sample J2ME code that shows various functionality of RMS.

By Henry Viewed: 6192 times Emailed: 198 times Printed: 214 times Bookmark and Share



The general flow of this MIDlet is  In the constructor (See RMSMIDlet), create and populate two record stores, one of personal contacts, the other with business contacts. Display the first screen. This screen shows a list of all RMS stores found in the MIDlet suite's name space. This screen allows the user to select a record store and either display pertinent information about the record store such as size, etc., or to view  the contents of the selected store. When the contents of a record store are viewed, they are sorted by last name, though this can be changed by instantiate a SimpleComparator object with the appropriate sort order parameter. Traversal from screen to screen is handled by RMSMIDlet, commandAction.

import java.lang.*;
import java.io.*;
import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import javax.microedition.midlet.*;

public class RMSMIDlet extends MIDlet implements CommandListener {
    private Display myDisplay;  // handle to the display
    private Alert alert;        // used to display errors

    // Our commands to display on every screen.
    private Command CMD_EXIT;
    private Command CMD_DETAILS;
    private Command CMD_OK;

    // Our screens
    private List mainScr;
    private List detailScr;
    private List dataScr;

    // An array of all RMS stores found in this
    // MIDlets name space.
    private String[] recordStoreNames;

    /**
     * Seed data for creating personal contacts RMS store
     */
    private final String personalContacts[] = {
        "John", "Zach", "2225556669",
        "Mark", "Lynn", "5125551212",
        "Joy", "Beth", "2705551234",
        "Abby", "Lynn", "4085558566",
    };

    /**
     * Seed data for creating business contacts RMS store
     */
    private final String businessContacts[] = {
        "Ted", "Alan", "4125552235",
        "Sterling", "Wincle", "9995559111",
        "Deborah", "Elaine", "4445552323",
        "Suzanne", "Melissa"," 5125556064",
        "Frank", "Kenneth", "7775551212",
        "Dwight", "Poe", "1115557234",
        "Laura", "Beth", "2055558888",
        "Lisa", "Dawn", "2705551267",
        "Betty", "June", "5555551556",
        "Yvonne", "Poe", "6665558888",
        "Lizzy", "Loo", "5025557971",
        "John", "Gerald", "3335551256",
    };

    /**
     * Display a warning on the screen and revert
     * to the main screen.
     *
     * s  A warning string to display
     */
    private void doAlert(String s) {
        alert.setString(s);
        myDisplay.setCurrent(alert, mainScr);
    }

    /**
     * Notify the system we are exiting.
     */
    private void doExit() {
        destroyApp(false);
        notifyDestroyed();
    }

    /**
     * In our simple MIDlet, all screens have the same commands,
     * with the possible exception of the detailScr.
     * 
     * Also set up the command listener to call commandAction.
     * See RMSMIDlet#commandAction
     */
    private void addCommonCommands(Screen s,
                                   boolean doDetails) {
        s.addCommand(CMD_OK);
        s.addCommand(CMD_EXIT);
        if (doDetails) {
            s.addCommand(CMD_DETAILS);
        }
        s.setCommandListener(this);
    }

    /**
     * The public constructor. In our constructor, we get
     * a handle to our display and create two record stores.
     * In the event of an error, we display an alert.
     */
    public RMSMIDlet() {
        CMD_EXIT = new Command("Exit", Command.EXIT, 3);
        CMD_DETAILS = new Command("Details", Command.SCREEN, 2);
        CMD_OK = new Command("OK", Command.OK, 1);
        myDisplay = Display.getDisplay(this);
        alert = new Alert("Warning");
        alert.setTimeout(2000);

        CreateAddressBook.createRecordStore("Personal",
                                            personalContacts);
        CreateAddressBook.createRecordStore("Business",
                                            businessContacts);

        // Now, get a list of RMS stores and add their
        // names to the mainScr.
        recordStoreNames = RecordStore.listRecordStores();
        mainScr = new List("Select RMS Store", List.IMPLICIT,
                           recordStoreNames, null);
        addCommonCommands(mainScr, true);
    }

    /**
     * Called by the system to start our MIDlet.
     */
    protected void startApp() {
        myDisplay.setCurrent(mainScr);
    }

    /**
     * Called by the system to pause our MIDlet.
     * No actions required by our MIDLet.
     */
    protected void pauseApp() {}

    /**
     * Called by the system to end our MIDlet.
     * No actions required by our MIDLet.
     */
    protected void destroyApp(boolean unconditional) {}

    /**
     * Generate a screen with a sorted list of the contents
     * of the selected RMS store identified by index
     * If any errors encountered, display an alert and
     * redisplay the mainScr.
     *
     * index  an index into recordStoreNames
     */
    public void genDataScr(int index) {
        SimpleComparator rc;
        RecordEnumeration re;
        RecordStore rs;
        dataScr = null;
        byte record[];

        try {
            rs = RecordStore.openRecordStore(
                                recordStoreNames[index], false);
        } catch (RecordStoreException e) {
            doAlert("Could not open " + recordStoreNames[index]);
            return;
        }

        // Create an enumeration that sorts by last name
        rc = new SimpleComparator(
                     SimpleComparator.SORT_BY_LAST_NAME);
        try {
            re = rs.enumerateRecords(null, rc, false);
        } catch (RecordStoreNotOpenException e) {
            doAlert("Could not create enumeration: " + e);
            return;
        }

        // Create a screen and append the contents of the
        // selected RMS store.
        dataScr = new List(recordStoreNames[index] + " Data",
                           List.IMPLICIT);
        addCommonCommands(dataScr, false);

        try {
            while (re.hasNextElement()) {
                byte[] b = re.nextRecord();
                dataScr.append(SimpleRecord.getFirstName(b) +
                               " " + SimpleRecord.getLastName(b),
                               null);
            }
        } catch (Exception e) {
            doAlert("Could not build list: " + e);
            dataScr = null;
        } finally {
            try {
                rs.closeRecordStore();
            } catch (RecordStoreException e) {}
        }
    }

    /**
     * Generate a screen that shows some of the details
     * of the selected RMS store.
     *
     * RMS store information displayed:
     * - name
     * - number of records
     * - size, in bytes
     * - available size, in bytes
     * - version number
     *
     * index  an index into recordStoreNames
     */
    public void genDetailScr(int index) {
        RecordStore rs;
        detailScr = null;

        try {
            rs = RecordStore.openRecordStore(
                                        recordStoreNames[index],
                                        false);
        } catch (Exception e) {
            doAlert("Could not open " + recordStoreNames[index]);
            return;
        }

        detailScr = new List(recordStoreNames[index] + " Details",
                             List.IMPLICIT);
        addCommonCommands(detailScr, false);


        try {
            detailScr.append("Name: "  + rs.getName(), null);
            detailScr.append("# recs: " +
                             rs.getNumRecords(), null);
            detailScr.append("Size: " + rs.getSize(), null);
            detailScr.append("Avail: " + 
                             rs.getSizeAvailable(),null);
            detailScr.append("Version: " +
                             rs.getVersion(), null);
        } catch (Exception e) {
            detailScr = null;
            doAlert("Failed to retrieve data");
            return;
        } finally {
            try {
                rs.closeRecordStore();
            } catch (RecordStoreException e) {}
        }
    }

    /***
     * Respond to command selections.
     * Commands are:
     * EXIT: if selected, then exit
             (see RMSMIDlet, doExit)
     * OK:   if selected, interpreted in the context of
     *       the current screen.
     *
     * This method implements a state machine that drives
     * the MIDlet from one state (screen) to the next.
     */
    public void commandAction(Command c,
                              Displayable d) {

        // Every screen has an EXIT command.
        // Handle this consistently for all screens.
        if (c == CMD_EXIT) {
            doExit();
            return;
        }

        // switch based on screen.
        if (d == mainScr) {

            // main screen: two commands to handle. If
            // OK was selected, then generate the dataScr
            // and make it active. If DETAILS was selected,
            // generate the detailScr and make it active.
            if ((c == List.SELECT_COMMAND) || (c == CMD_OK)) {
                genDataScr(mainScr.getSelectedIndex());
                myDisplay.setCurrent(dataScr);
            } else if (c == CMD_DETAILS) {
                genDetailScr(mainScr.getSelectedIndex());
                myDisplay.setCurrent(detailScr);
            }

        } else if (d == detailScr) {

            // If OK selected, go back to mainScr
            if (c == CMD_OK) {
                myDisplay.setCurrent(mainScr);
            }

        } else if (d == dataScr) {

            // If OK selected, go back to mainScr
            if (c == CMD_OK) {
                myDisplay.setCurrent(mainScr);
            }

        }
    }
}




Comments(11)


1. hello
thanks for your code
i need complete code at above
please send to me
CreateAddressBook code
thanks a lot

By: m_karimi at 2008-10-24 12:08:06
2. Is it possible for you to create for me a mobile application?

By: Meme at 2008-12-23 06:24:42
3.
thanks for your code
could you send me the complete code at above, please??

By: nocturne at 2009-01-09 01:57:05
4. Please, if it is incomplete, can you please send me the complete version of this code?
I am doing some tests.

By: Marcio at 2009-03-01 09:06:45
5. thanks for your code
could you send me the complete code at above. I would really appreciate it..

thanks!

lots of love,
jeng

By: diana jeng at 2009-04-21 03:50:39
6. is anyone going to post the complete version of this tutorial, or what ??????

By: anon at 2009-04-21 12:26:51
7. I need the multiple record store RMS code.Pls help out.

By: Raghuvir at 2009-05-13 23:03:44
8. hello
thanks for your code. Please could any send to me
CreateAddressBook code. Because I can't run the example!
thanks a lot


By: Bruno at 2009-05-28 15:38:46
9. Thank you for the code. Could you please send me completed code (CreateAddressBook class).
Thank you so much!

By: Ying at 2009-08-17 13:58:16
10. could you send me a code for a music video mobile application?
i'll wait it.
thanks.

By: Christian at 2009-08-28 23:03:45
11. Full Code: http://www.java2s.com/Code/Java/J2ME/AsimpleclassthatshowsvariousfunctionalityofRMS.htm

By: Mehmet at 2009-10-20 07:58:26

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:


Enter Code:
The Captcha image

Latest Tutorials

[2009-05-29]Adding your own Application icon for your J2ME application (jar file)
[2008-08-18]Play a multimedia file in J2ME Program (Audio/Video) using MMAPI
[2008-08-01]Datagrams in J2ME (UDP Programming sample)
[2008-08-01]Client Server in J2ME (Socket Programming sample)
[2008-08-01]Using HttpConnection in J2ME (Retrieve web content from a website to a phone)
[2008-08-01]Using HTTP vs UDP vs Socket in J2ME
[2008-08-01]RMSCookieConnector - Using Cookies in J2ME
[2008-07-29]POST UTF-8 encoded data to the server in J2ME
[2008-07-10]lists, forms, choices, gauges, text fields, text boxes in J2ME
[2008-07-10]Using List to create a Menu and Menu items in J2ME
[2008-07-10]Using alerts and tickers in J2ME
[2008-07-07]J2ME Canvas sample to show games programming in J2ME
[2008-07-07]Timer and TimerTask example in J2ME
[2008-06-27]List of GPRS Access points for all countries
[2007-12-06]What is J2ME?

More Latest News


Most Viewed Articles (in last 30 days)
Getting Started with J2ME
Client Server in J2ME (Socket Programming sample)
GUI components and menu based J2ME Applications.
What is J2ME?
RMS Basics in J2ME
Adding your own Application icon for your J2ME application (jar file)
J2ME Canvas sample to show games programming in J2ME
Using HttpConnection in J2ME (Retrieve web content from a website to a phone)
Play a multimedia file in J2ME Program (Audio/Video) using MMAPI
Timer and TimerTask example in J2ME
Using List to create a Menu and Menu items in J2ME
Types of configurations in J2ME
Download a file over a network in J2ME midlet
Sample J2ME code that shows various functionality of RMS.
Your first J2ME program and a midlet lifecycle explained.
Most Emailed Articles (in last 30 days)
What is J2ME?
Download a file over a network in J2ME midlet
How to load J2ME applications to the IDEN handsets
Y.S. Sun Green Building Research Center
Getting Started with J2ME
Types of configurations in J2ME
'LINK.EXE' is not recognized as an internal or ext
Sample Java program shows how to Read a file over a network using J2ME midlet
Sample J2ME code that shows various functionality of RMS.
GUI components and menu based J2ME Applications.
RMS Basics in J2ME
UDP Datagram sample in J2ME
Your first J2ME program and a midlet lifecycle explained.
The MIDP Networking Model in J2ME
Internationalization Support in J2ME MIDP