Sample J2ME code that shows various functionality of RMS.

By: Henry Emailed: 1672 times Printed: 2152 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

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

        }
    }
}

J2ME Home | All J2ME Tutorials | Latest J2ME Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(27)


1. View Comment

hello
thanks for your code
It works for me. Thanks a lot


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

Is it possible for you to create for me a mobile application?

View Tutorial          By: Meme at 2008-12-23 06:24:42
3. View Comment

thanks for your code
could you send me the complete code at above, please??


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

Please, if it is incomplete, can you please send me the complete version of this code?
I am doing some tests.


View Tutorial          By: Marcio at 2009-03-01 09:06:45
5. View Comment

thanks for your code
could you send me the complete code at above. I would really appreciate it..

thanks!

lots of love,
jeng


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

is anyone going to post the complete version of this tutorial, or what ??????

View Tutorial          By: anon at 2009-04-21 12:26:51
7. View Comment

I need the multiple record store RMS code.Pls help out.

View Tutorial          By: Raghuvir at 2009-05-13 23:03:44
8. View Comment

hello
thanks for your code. Please could any send to me
CreateAddressBook code. Because I can't run the example!
thanks a lot


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

Thank you for the code. Could you please send me completed code (CreateAddressBook class).
Thank you so much!


View Tutorial          By: Ying at 2009-08-17 13:58:16
10. View Comment

could you send me a code for a music video mobile application?
i'll wait it.
thanks.


View Tutorial          By: Christian at 2009-08-28 23:03:45
11. View Comment

thanq for this tutorial. It is very useful. But i'm looking for tutorial how to use rms to store 'textfill' data..for example..String english = "Hello World";
pls..guide me


View Tutorial          By: syahmi at 2010-03-06 02:55:05
12. View Comment

hello
i am developing a budget application for a mobile phone. What data must i store?


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

Dear Sir,

This code is so good. but it is not working without the CreateAddressBook class. So plz send me the code of CreateAddressBook on my id.


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

Hi There Busy doing a project and found that i couldn't use the .Properties Class, in doing some research i find that your code is the best way to move forward with the project, would you be so kind as to send me the code for CreateAddressBook class. Thanks in advance...

View Tutorial          By: Steven Owen Nell at 2010-09-05 13:32:01
15. View Comment

its is good..I am developing a Form based application in that i am using RMS for storing the data temporarily...can u please send me the code for storing data from simple application contains name age sex in mobile using rms.....please help me

View Tutorial          By: Bhavani at 2010-10-18 01:39:41
16. View Comment

I want to creat a bilingual dictionary for mobile with java and using netbeans program. does any body have a full code of dictionary as mentioned above?
I would appreciate if you help as i have no time and this is my final project.

thanks,
maryam


View Tutorial          By: Maryam at 2011-01-25 02:28:44
17. View Comment

not work

View Tutorial          By: kkbb at 2011-03-12 03:52:06
18. View Comment

Cant be compiled, i got error with this msg:. cannot determine simple type 'SimpleComparator'.. Blah blah
:(


View Tutorial          By: ken at 2011-04-17 04:32:36
19. View Comment

Dear sir/madam

can you please show me how to code a client/server application
examples and tutorials with J2ME

kind regards
k seboya


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

Can u send total code, i am in critical position now if u send that code it will be usefull to me

View Tutorial          By: ram at 2011-05-16 07:07:10
21. View Comment

i need a J2me PIM for accessing phone contact...
please..................


View Tutorial          By: shafique at 2011-06-28 04:11:55
22. View Comment

dear sir/madam
I am using netbeans IDE 7.0 to develop mobile applications. please send me how to create a RMS to store data. And send me the place in Where it was located in IDE.


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

I am using RMS but in my case i have to show 10 records based on the conditions out of 10000 records here i have to traverse through all records that slow downs the system. is there any other options where i can set the criteria to read only 10 records ? any other way to connect with the database...?

View Tutorial          By: Hemant at 2012-08-14 05:46:40
24. View Comment

Hello guys, the code above is the full complete code.
It works for me.


View Tutorial          By: Dalma at 2012-10-03 02:50:33
25. View Comment

Can i have CreateAddressBook.java?? really need it.. send to my email if possible..

View Tutorial          By: KIM at 2012-12-02 11:45:20
26. View Comment

Hello,
could you send me the complete code to my mail pls..

Thanks
Sanjay


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

what we have to write in simple comparator class can u explain in briefly thank you

View Tutorial          By: shiva at 2015-04-18 09:19:17

Your name (required):


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


Your sites URL (optional):


Your comments:



More Tutorials by Henry
Generating Your Key Pair example using keytool in Java
Summary of Operators in Java
JDBC Basics and JDBC Components
The IterationTag Interface in JSP
Trigonometric, Hyperbolic, Exponential and Logarithmic Functions in C
Using Bit-field in C
Java Beans and the Expression Language
Initialization of Variables in C
Creating Struts Modules
else if statement in C
Line Counting sample program in C
Accessing Context Data in Beans using JSF
Using peek() and putback() with cin in C++
Internationalization Support in J2ME MIDP
java.lang.SecurityException: MIDP lifecycle does not support system exit.

More Tutorials in J2ME
Code sample to Send SMS from a J2ME application.
Adding your own Application icon for your J2ME application (jar file)
Play a multimedia file in J2ME Program (Audio/Video) using MMAPI
Datagrams in J2ME (UDP Programming sample)
Client Server in J2ME (Socket Programming sample)
Using HttpConnection in J2ME (Retrieve web content from a website to a phone)
Using HTTP vs UDP vs Socket in J2ME
RMSCookieConnector - Using Cookies in J2ME
POST UTF-8 encoded data to the server in J2ME
lists, forms, choices, gauges, text fields, text boxes in J2ME
Using List to create a Menu and Menu items in J2ME
Using alerts and tickers in J2ME
J2ME Canvas sample to show games programming in J2ME
Timer and TimerTask example in J2ME
List of GPRS Access points for all countries

More Latest News
Most Viewed Articles (in J2ME )
Sample J2ME code that shows various functionality of RMS.
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
'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
A sample J2ME midlet that shows an example of using a Timer and a TimerTask.
GUI components and menu based J2ME Applications.
Your first J2ME program and a midlet lifecycle explained.
java.lang.SecurityException: MIDP lifecycle does not support system exit.
How to get the CLDC and MIDP version from a J2ME program
DateField sample program in J2ME
StringItem sample program in J2ME
Gauge sample program in J2ME
Most Emailed Articles (in J2ME)
StringItem sample program in J2ME
What is J2ME?
How to load J2ME applications to the IDEN handsets
Gauge sample program in J2ME
Ticker sample program in J2ME
Sample program to draw a arc in J2ME
Using HttpConnection in J2ME (Retrieve web content from a website to a phone)
Using HTTP vs UDP vs Socket in J2ME
RMSCookieConnector - Using Cookies in J2ME
Play a multimedia file in J2ME Program (Audio/Video) using MMAPI
'LINK.EXE' is not recognized as an internal or ext
How to get the CLDC and MIDP version from a J2ME program
DateField sample program in J2ME
Image and ImageItem sample program in J2ME
TextBox sample program in J2ME