An Open Source Fascicule

Author: Jay Mahadeokar


Here i present a small tutorial to built utility applications using the RMS facility
in J2ME and NetBeans.


Table Of Content:

1. Introduction to RMS.

2. Aim.

3. Tools needed.

4. Creating the basic classes.

5. Creating the basic display containers.

6. Linking the display items.

7. Adding RMS functionality in the event handlers using the classes created.

8. Compile and run the project.

9. Future scope.

1. Introduction to RMS:

Small computing devices do not have a robust file system and therefore are unable to store information in the manner that we are accustomed to when working with a PC, server, and other traditional computing devices. The Record Management System (RMS) provides a file system–like environment that is used to store and maintain persistence in a small computing device. We can insert records, read records, search for particular records, and sort records stored by the RMS.

RMS stores information in a record store. A record store is a collection of records organized as rows (records) and columns (fields). RMS automatically assigns to each row a unique integer that identifies the row in the record store, which is called the record ID.

2. Aim:

To create a simple application in J2ME that will provide facility for storing expenses. The application will provide options for storing the reason for expens and the amount spent using an easy interface.


3. Tools Needed:

  1. NetBeans IDE 6.0/ 6.1
  2. Mobility Pack.

4. Creating the basic classes:

Create New MIDP application. Name it as ExpensesApp.

I. A HelloMIDlet.java file will be created in the src\hello\ package.

II. Create a new java file: Expenses.java.

III. Paste the following code there:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreFullException;
import javax.microedition.rms.RecordStoreNotFoundException;

/**
* This class is the base for handling the storage part of our
* Expenses application
*
* It handles all the writing and reading of the data from
* record store.
*
* An instance of this class will be created in the main Midlet
*
* @author jay
*/
public class Expenses {

/**
* The reason for which the expense was incurred
*/
String Reason = null;

/**
* The Amount of money that spent for the particular expense
*/
int Amount ;

/**
* Method to write the st to disk
*/
void writeToDisk() throws IOException {
try {
RecordStore ExpenseRecord = RecordStore.openRecordStore("ExpRecord", true);
//Creating output streams
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream os = new DataOutputStream(baos);
//Writing value to be saved to output stream
os.writeUTF(this.Reason);
os.writeInt(this.Amount);

//close stream
os.close();

byte[] data = baos.toByteArray();

//Write the record to the record store
int id = ExpenseRecord.addRecord(data, 0, data.length);
//Close Record store
ExpenseRecord.closeRecordStore();
} catch (RecordStoreFullException ex) {
ex.printStackTrace();
} catch (RecordStoreNotFoundException ex) {
ex.printStackTrace();
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}

/**
*Method to read record from disk and
* initialize values of member variables
* @param RecordID the id of the record to be read
*/
int readFromDisk(int RecordID) throws IOException {
boolean flag = true;
while (flag) {
try {
RecordStore ExpenseRecord = RecordStore.openRecordStore("ExpRecord",false);
//read get the record, specified by RecordID in a byte array
byte[] data = ExpenseRecord.getRecord(RecordID);


//If record is read, RecordID is valid and flag
//needs to be reset
flag = false;

DataInputStream is = new DataInputStream(new ByteArrayInputStream(data));

//retrieve

this.Reason = is.readUTF();
this.Amount = is.readInt();


//close stream
is.close();
ExpenseRecord.closeRecordStore();
} catch (RecordStoreFullException ex) {
ex.printStackTrace();
} catch (RecordStoreNotFoundException ex) {

ex.printStackTrace();
} catch (InvalidRecordIDException ex) {
//If invalid recordID, it means that the
//the record was deleted, and we need to search
//in next id for a proper record.
RecordID++;
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}
//Return the ID of next record
return (++RecordID);
}
}
You may want to add functionality to store date, place etc. Make the corresponding entries here.

IV. Create a new java file: ManageExpenses.java.

package hello;
import java.io.IOException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreFullException;
import javax.microedition.rms.RecordStoreNotFoundException;

/**
* This class is the base for handling the storage part of our
* Expenses application
*
* An instance of this class will be created in the main Midlet
*
* @author jay
*/
public class ManageExpenses {

/**
* The array corresponding that will store myExpense objects
*/
Expenses myExpense[] = null;



/**
* count: To indicate the total number of records
* added: To indicate number of records added since the midlet
* was last opened
*/
int count;

int added;

/**
* Constructor.
*/
ManageExpenses(){
myExpense = new Expenses[20];
count = 0;
added = 0;
};

/**
* Method to write the current state of Expense object
* to a record store.
* This is similar to Serialization of an object
*/
void writeToDisk() {
for (int i = count-added; i < count; i++) {
try {
myExpense[i].writeToDisk();
} catch (IOException ex) {

}
}
}

/**
* Method to read from disk and initialize Expense object
* It is like Deserialization
*/
void readFromDisk() {
try {

//Open Record Store
RecordStore SubjectRecord = RecordStore.openRecordStore("ExpRecord", false);

//Get the length of Record Store in a Length member variable
int Length = SubjectRecord.getNumRecords();

//Start From RecordID 1
int RecordID = 1;

for (int i = 0; i < Length; i++) {
myExpense[i] = new Expenses();
RecordID = myExpense[i].readFromDisk(RecordID);
count++;

}


//Close Record Store
SubjectRecord.closeRecordStore();

} catch (IOException ex) {
ex.printStackTrace();
} catch (RecordStoreFullException ex) {
ex.printStackTrace();
} catch (RecordStoreNotFoundException ex) {
ex.printStackTrace();
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}


/**
* @param r
* @param a
* @param d
*
* To add a Expense entry in the list
*/
void addExpense(String r, String a)
{

Expenses e = new Expenses();
//e.id = 0;
e.Reason = r;
e.Amount = Integer.parseInt(a);
myExpense[count++] = e;
added++;

}

}

5. Creating the basic display containers:

I. Open the HelloMIDlet.java and click on the Flow tab you will find something like this:







II. Now go to the palette window and select the list option. Add it to the file by clicking anywhere on the Flow tab as shown:





Rename the List name as well as the instance name as menu. This can be done by right clicking on the list and selecting properties option. This list will be used to display the main menu.

III. Now create an exitCommand for the Menu List Item. This can be done by:

RightClick >> New/Add >> exitCommand as shown:

V. Similarly add two List Elements to Menu and rename them as Add Expense and View Expenses.

VI. Add another List item and rename it as viewExpense. Add backCommand to it. Rename it as backCommandView.

Go to edit view.

Right-click and add two text-fields.

Set their instance names and Labels to “Reason” and “Amount”.

VII. Now go to the Palette tab and add a new Form.

Rename it as addExpenseForm.

Give the title as Add Expense.

Add cancelCommand and okCommand to the form in similar way as described before.

Rename them as cancelCommandAddForm and okCommandAddForm.

VIII. Add a splashScreen from the palette.

Right click splashScreen >> Select Edit.

There set the message to be displayed as “Expense added successfully!”

IX. Finally delete the form that was previously present.

The layout will be as follows:

6. Linking the display items:

Now we come to the most interesting and easy part of creating the application. We will link the display items that we created. This is an easy drag and drop process.

Left click on the event and drag it to the item you want to be displayed on occurrence of that event. The display item will be automatically linked with the event.

Example: On the Started event of Mobile Device item, we want the menu to be displayed.

So, right-click on Started button and drag it to menu.

Create following links in a similar fashion:

Event

Display Item

1. Mobile Device: Started()

menu

2. menu: exitCommandMenu()

Mobile Device

3. menu: Add Expense()

addExpenseForm

4. addExpenseForm: cancelCommandaddForm()

menu

5. addExpenseForm: okCommandAddForm()

splashScreen

6. splashScreen: DISMISS_COMMAND

Menu

7. menu: View Expenses()

viewExpenses

8. viewExpenses: backCommandView()

Menu

The window will look like as follows:

(Note: To get the items arranged in a systematic fashion, click on the button highlighted in red circle in figure)

7. Adding RMS functionality in the event handlers using the classes created.

I. Open the Source Tab.

II. Add variables:

//To indicate that application has started for first time

private boolean flag = false;

//Array of expenses

private ManageExpenses myexp = new ManageExpenses();

III. In the exitMIDlet() function add the following code:

try {
myexp.writeToDisk();
} catch (Exception ex) {
ex.printStackTrace();
}

IV. Go to Generate Method: menuAction.

Place the code below as shown in next figure

if(!flag)
{
myexp.readFromDisk();
flag = true;
}
for(int i=viewExpense.size();i
{
viewExpense.append(myexp.myExpense[i].Reason+" : "+myexp.myExpense[i].Amount , null);
}

V. Similarly expand Generate Method: CommandAction for Displayables.

Add following code as shown.

myexp.addExpense(Reason.getString(),Amount.getString() );
Amount.setString("");
Reason.setString("");

8. Final Step: Compile and run the project.

You can see following outpot when you launch the Midlet.

9. Future scope:

The functionality can be extended so as to store expenses according to date, give useful information from the stored expenses data like expenses for a particular month etc.


Note: Special thanks to Vasusen Patil who literally dragged me into mobile programming and has always been there for help.

14 comments

  1. Sivaprakash  

    package hello;
    import java.io.IOException;
    import javax.microedition.rms.RecordStore;
    import javax.microedition.rms.RecordStoreException;
    import javax.microedition.rms.RecordStoreFullException;
    import javax.microedition.rms.RecordStoreNotFoundException;

    /**
    * This class is the base for handling the storage part of our
    * Expenses application
    *
    * An instance of this class will be created in the main Midlet
    *
    * @author jay
    */

    public class ManageExpenses {

    /**
    * The array corresponding that will store myExpense objects
    */

    Expenses myExpense[] = null;


    /**
    * count: To indicate the total number of records
    * added: To indicate number of records added since the midlet
    * was last opened
    */
    int count;

    int added;


    /**
    * Constructor.
    */

    ManageExpenses(){
    myExpense = new Expenses[20];
    count = 0;
    added = 0;
    };

    /**
    * Method to write the current state of Expense object
    * to a record store.
    * This is similar to Serialization of an object
    */
    void writeToDisk() {
    for (int i = count-added; i < style=""> try {
    myExpense[i].writeToDisk();
    } catch (IOException ex) {
    }
    }
    }

    /**
    * Method to read from disk and initialize Expense object
    * It is like Deserialization
    */
    void readFromDisk() {
    try {
    //Open Record Store
    RecordStore SubjectRecord = RecordStore.openRecordStore("ExpRecord", false);
    //Get the length of Record Store in a Length member variable
    int Length = SubjectRecord.getNumRecords();
    //Start From RecordID 1
    int RecordID = 1;
    for (int i = 0; i < style=""> myExpense[i] = new Expenses();
    RecordID = myExpense[i].readFromDisk(RecordID);
    count++;

    }

    //Close Record Store
    SubjectRecord.closeRecordStore();

    } catch (IOException ex) {
    ex.printStackTrace();
    } catch (RecordStoreFullException ex) {
    ex.printStackTrace();
    } catch (RecordStoreNotFoundException ex) {
    ex.printStackTrace();
    } catch (RecordStoreException ex) {
    ex.printStackTrace();
    }
    }

    /**

    * @param r

    * @param a

    * @param d

    *

    * To add a Expense entry in the list

    */

    void addExpense(String r, String a)

    {

    Expenses e = new Expenses();

    //e.id = 0;

    e.Reason = r;

    e.Amount = Integer.parseInt(a);

    myExpense[count++] = e;

    added++;

    }

    }


    Hi this code has error.please chet it and post

  2. Jay  

    Thanks for pointing out..

    I think I have made necessary changes..

    I will also try to provide the built project soon..

    As I am new to blogging I dont know how to upload zip files (Sorry for that!)

  3. Costy  

    if(!flag)
    {
    myexp.readFromDisk();
    flag = true;
    }
    for(int i=viewExpense.size();i
    {
    viewExpense.append(myexp.myExpense[i].Reason+" : "+myexp.myExpense[i].Amount , null);
    }

    The for statement is incorrect. Please correct it, and tell me.

  4. DZ  

    Hello,
    Great post! See on June 14th. where there is a line of code not valid.

    for(int i=viewExpense.size();i

    Have you had an opportunity to update your blog with a fix? Thanks again.
    /dz

  5. Jay Mahadeokar  

    Hello all.

    Please find the project code here: http://blogs.sun.com/jaysblog/entry/using_rms_in_netbeans_mobility

  6. prateek  

    Hi,Jay.RMS tutorial by you was wonderful,Can you suggest how to incorporate with date Functionality and to save the date in Record store.It would be nice if you help me in getting this..............

  7. Adi  

    Oes Tsetnoc one of the ways in which we can learn seo besides Mengembalikan Jati Diri Bangsa. By participating in the Oes Tsetnoc or Mengembalikan Jati Diri Bangsa we can improve our seo skills. To find more information about Oest Tsetnoc please visit my Oes Tsetnoc pages. And to find more information about Mengembalikan Jati Diri Bangsa please visit my Mengembalikan Jati Diri Bangsa pages. Thank you So much.
    Oes Tsetnoc | Semangat Mengembalikan Jati Diri Bangsa

  8. Nadeem1414  

    http://www.mobile-phone.pk i have visited to this site which founded very interested and informative.

  9. kim  

    what about deleting an expense?

  10. Replica Watches  

    Knockoff. He mean still. Replica juicy couture Antique, thinking gruen of you left of pocket, held his watches and pointed as. Jacbo watches He intend a pouring off away. Wholesale replica coach handbags Even me asked he away. Cheapest watches in uk Walk she to she, could he? Not apparently another country for the college watches deformity, and his passwords temple away. Purse replica The he should nail. Zelda Sword Replica..

  11. Justin  

    Thanks for sharing it to us. I would like to create this kind of utility for mobiles using NetBeans. I will apply it in my next project. Viagra Generic Viagra

  12. yurake  

    try using women's health

  13. yurake  

    led flashlight for all

  14. adeoe  

    Thanks for pointing out..

    I think I have made necessary changes..

    I will also try to provide the built project soon..

    As I am new to blogging I dont know how to upload zip files (Sorry for that!)Guild wars 2 gold
    Buy guild wars 2 gold

Post a Comment

Subscribe to: Post Comments (Atom)