Sample J2ME code that shows various functionality of RMS.

By: Henry Emailed: 1788 times Printed: 2623 times    

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);
            }

        }
    }
}

Most Viewed Articles (in J2ME )

Latest Articles (in J2ME)

Comment on this tutorial

Subscribe to Tutorials

Related Tutorials

Archived Comments

1. hello
thanks for your code
It works

View Tutorial          By: m_karimi at 2008-10-24 12:08:06

2. Is it possible for you to create for me a mobile a
View Tutorial          By: Meme at 2008-12-23 06:24:42

3. thanks for your code
could you send me the

View Tutorial          By: nocturne at 2009-01-09 01:57:05

4. Please, if it is incomplete, can you please send m
View Tutorial          By: Marcio at 2009-03-01 09:06:45

5. thanks for your code
could you send me the

View Tutorial          By: diana jeng at 2009-04-21 03:50:39

6. is anyone going to post the complete version of th
View Tutorial          By: anon at 2009-04-21 12:26:51

7. I need the multiple record store RMS code.Pls help
View Tutorial          By: Raghuvir at 2009-05-13 23:03:44

8. hello
thanks for your code. Please could an

View Tutorial          By: Bruno at 2009-05-28 15:38:46

9. Thank you for the code. Could you please send me c
View Tutorial          By: Ying at 2009-08-17 13:58:16

10. You can find the full source here...
http:/

View Tutorial          By: Sudarshan at 2009-08-24 06:34:48

11. could you send me a code for a music video mobile
View Tutorial          By: Christian at 2009-08-28 23:03:45

12. Hello guys, the code above is the full complete co
View Tutorial          By: Dalma at 2012-10-03 02:50:33

13. thanx for the code, but its better if u can post t
View Tutorial          By: anna at 2009-12-17 07:26:04

14. thanq for this tutorial. It is very useful. But i'
View Tutorial          By: syahmi at 2010-03-06 02:55:05

15. hello
i am developing a budget application

View Tutorial          By: anu at 2010-04-16 04:26:36

16. Dear Sir,

This code is so good. but

View Tutorial          By: Jai Singh Saini at 2010-05-06 06:13:45

17. Hi There Busy doing a project and found that i cou
View Tutorial          By: Steven Owen Nell at 2010-09-05 13:32:01

18. its is good..I am developing a Form based applicat
View Tutorial          By: Bhavani at 2010-10-18 01:39:41

19. its is good..I am developing a Form based applicat
View Tutorial          By: Bhavani at 2010-10-18 01:40:14

20. can i store records in the mobile some where if it
View Tutorial          By: sanjeev at 2010-11-26 02:57:15

21. can i store records in the mobile some where if it
View Tutorial          By: sanjeev at 2010-11-26 02:58:20

22. I want to creat a bilingual dictionary for mobile
View Tutorial          By: Maryam at 2011-01-25 02:28:44

23. please sent me a complite source..
at my e-

View Tutorial          By: androww at 2011-01-25 09:35:02

24. not work
View Tutorial          By: kkbb at 2011-03-12 03:52:06

25. Cant be compiled, i got error with this msg:. cann
View Tutorial          By: ken at 2011-04-17 04:32:36

26. Dear sir/madam

can you please show

View Tutorial          By: kgothatso at 2011-05-13 17:44:04

27. Dear sir/madam

can you please show

View Tutorial          By: kgothatso at 2011-05-13 17:46:19

28. Can u send total code, i am in critical position n
View Tutorial          By: ram at 2011-05-16 07:07:10

29. i need a J2me PIM for accessing phone contact... <
View Tutorial          By: shafique at 2011-06-28 04:11:55

30. dear sir/madam
I am using netbeans IDE 7.0

View Tutorial          By: bangaram at 2011-07-19 12:03:04

31. I am using RMS but in my case i have to show 10 re
View Tutorial          By: Hemant at 2012-08-14 05:46:40

32. Can i have CreateAddressBook.java?? really need it
View Tutorial          By: KIM at 2012-12-02 11:45:20

33. Hello,
could you send me the complete code

View Tutorial          By: Sanjay at 2013-04-19 07:28:12

34. what we have to write in simple comparator class
View Tutorial          By: shiva at 2015-04-18 09:17:09

35. what we have to write in simple comparator class
View Tutorial          By: shiva at 2015-04-18 09:18:48

36. what we have to write in simple comparator class
View Tutorial          By: shiva at 2015-04-18 09:19:17

37. I want to know to create a multiple midlets in sin
View Tutorial          By: naveen at 2016-10-07 19:25:31

38. could you share the complete code to my mail ID
View Tutorial          By: nikhitha at 2017-07-27 19:03:01