Implementing Phone Book application in J2ME (step-2)

This post continues my previous post about “Implementing Phone Book application in J2ME (step-1). So in this post you will be able to get to know how to put your new contacts in to an array type according to a sorting order. The next thing I am going to show is how to use the Search option which I promised you in my previous post.

The classes that I am going to introduce newly in this post are;

  • Vector

The interfaces that I am going to introduce newly in this post are;

  • ItemStateListener
  • RecordComparator
  • RecordFilter

Following interfaces will give you clear understanding what I am going to do today.

Adding, Sorting and Searching

Figure 1

The contacts I added not according to the displaying order. I simply add a new contact to the Vector array. Then from the help of compare method in RecordComparator interface, it sort according to the name and put it in the correct place. As you know, Vector adds elements according to the index order. But we need lexicographically sorting order to store our contacts. That is why we used compare method.

New contact contains mainly the name and the phone number attributes. Therefore we need a mechanism to add those details as together in one element of the Vector. What I have done here was create a class called ContactDetails and with in that class declare the attributes that I want to add as one element in the Vector array. Here is the code of the class

package anuja;

 * @author Anuja
class ContactDetails {
    private int contactId;
    private String contactName;
    private String contactNumber;

     * @return the contactId
    public int getContactId() {
        return contactId;

     * @param contactId the contactId to set
    public void setContactId(int contactId) {
        this.contactId = contactId;

     * @return the contactName
    public String getContactName() {
        return contactName;

     * @param contactName the contactName to set
    public void setContactName(String contactName) {
        this.contactName = contactName;

     * @return the contactNumber
    public String getContactNumber() {
        return contactNumber;

     * @param contactNumber the contactNumber to set
    public void setContactNumber(String contactNumber) {
        this.contactNumber = contactNumber;

Next thing I have implemented was the Search option. In the second interface of the Figure 1 you can see it clearly. When I type a letter, the relevant contacts in that letter will be filtered and display. To achieve that option we have to use matches method in RecordFilter interface. If there is a change of an item in our interfaces that can be identified by using ItemStateListner interface.

Here is the full code to achieve those functions. I encourage you to copy the code and paste it on the NetBeans IDE. Then you will be able to clearly identify the comments and the code.

package anuja;

import java.util.Vector;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemStateListener;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.RecordComparator;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordFilter;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;

 * @author Anuja
public class SearchContact extends MIDlet implements CommandListener, RecordComparator, ItemStateListener, RecordFilter {

    private Display display;
    private ChoiceGroup searchChoice;
    private Form searchForm;
    private TextField searchTxtField;
    private Command exitCmd;
    private Command addContactCmd;
    private Form addContactForm;
    private TextField nameTxtField;
    private TextField numberTxtField;
    private Command backCmd;
    private Command saveCmd;
    private String nameStr;
    private String numberStr;
    private Alert addAlert;
    private RecordStore openRecStore;
    private Vector vectorArray;

    // Need to declare & initialize when we use this with startsWith()
    // If we don't initialize, it will give us NullPointerException
    // Default value of String is null although other data types have some values like int have 0 as default value
    private String filterStr = "";

    public void startApp() {
        display = Display.getDisplay(this);

        // --------------------- Search Contact Form ---------------------------

        searchForm = new Form("Search Contact");
        searchTxtField = new TextField("Search Here", "", 30, TextField.ANY);

        searchChoice = new ChoiceGroup("", Choice.EXCLUSIVE);
        //searchChoice.append("Anuja", null);

        exitCmd = new Command("Exit", Command.EXIT, 7);
        addContactCmd = new Command("Add", Command.OK, 4);

        // If there is a change of the items here it will call the itemStateChanged()


        //-------------------- Add Contact Form --------------------------------

        addContactForm = new Form("Add Contacts");
        nameTxtField = new TextField("Name", "", 80, TextField.ANY);
        numberTxtField = new TextField("Number", "", 20, TextField.PHONENUMBER);

        backCmd = new Command("Back", Command.BACK, 2);
        saveCmd = new Command("Save", Command.OK, 4);


        //-------------------- Open a RecordStore ------------------------------

        try {
            openRecStore = RecordStore.openRecordStore("Contacts", true);
        } catch (RecordStoreException ex) {


    public void pauseApp() {

    public void destroyApp(boolean unconditional) {

    public void commandAction(Command c, Displayable d) {
        if (c == exitCmd) {
        } else if (c == addContactCmd) {
        } else if (c == backCmd) {
        } else if (c == saveCmd) {

            //------------------ Get the inputs ------------------------
            nameStr = nameTxtField.getString();
            numberStr = numberTxtField.getString();
            String fullDetails = nameStr + "*" + numberStr;

            // Can add the name to the ChoiceGroup like below or by getting it from the RecordStore like in loadContacts()
            //searchChoice.append(nameStr, null);

            addAlert = new Alert("Added to the Contacts");
            display.setCurrent(addAlert, searchForm);


//--- To add to the RecordStore we need to convert the String to byte array ---
            byte[] byteArray = fullDetails.getBytes(); // String class

//--- Add a new record to the RecordStore
            try {
                openRecStore.addRecord(byteArray, 0, fullDetails.length()); // RecordStore class
            } catch (RecordStoreException ex) {

            // If you remove the following line, the newly adding contacts are not display. They will display after another contact being added

    private void loadContacts() {
        // Add following line to ignore the same contact add twice

        vectorArray = new Vector();

        try {
//---  Returns an enumeration for traversing a set of records in the record store in an optionally specified order.
            //RecordEnumeration enuRec = openRecStore.enumerateRecords(this, this, true);
            RecordEnumeration enuRec = openRecStore.enumerateRecords(this, this, true);

            while (enuRec.hasNextElement()) {
                try {
                    // Take a recoed and convert it from byte array to String
                    //byte[] nextRec = enuRec.nextRecord();
                    //String nextRecStr = new String(nextRec);

                    // Returns the recordId of the next record in this enumeration,
                    // Where next is defined by the comparator and/or filter supplied in the constructor of this enumerator
                    int recordId = enuRec.nextRecordId(); // Method in RecordEnumeration
                    byte[] nextRec = openRecStore.getRecord(recordId); // Method in RecordStore
                    String nextRecStr = new String(nextRec);

                    // Seperate Name and the Phone number from the String
                    // We have to assign the results after substring because Strings are immutable
                    // That means when we assign a String to a variable it will "never change"
                    String takeName = nextRecStr.substring(0, nextRecStr.indexOf("*"));
                    // nextRecStr.substring(0, nextRecStr.indexOf("*"));
                    // There is no error in the above line. It will create a String object as well.
                    // But we can't access that object and it's get lost
                    String takeNumber = nextRecStr.substring(nextRecStr.indexOf("*") + 1, nextRecStr.length());

                    // Add the Name in to ChoiceGroup
                    searchChoice.append(takeName, null);

                    // Create a Vector class to put contacts. We use Vector because it is a growable array
                    // But you can't initialize it here. Because we are calling removeAllElements() in above.
                    // So have to create above all the related methods in Vector class
                    // See first few lines after begining of loadContacts()

                    // We need to put three variables (name, number and id) in to one element in the Vector array.
                    // In addElement method we can only pass an Object.
                    // So the best option is create an Object which is having above mentione attributes (name, number and id)
                    ContactDetails conDet = new ContactDetails();

                    // Add attributes in the ContactDetails class to the Vector array
                    // But it adds the specified component to the end of this vector, increasing its size by one.
                    // Simply, Vector elements are ordered by index
                    // But in a PhoneBook, we don't want to add a contact as it is.
                    // We need to sort according to the name as an example first we expect to see the names begins with "A"
                    // Here we need the compare(byte[] rec1, byte[] rec2) method which comes under RecordComparator

                } catch (RecordStoreException ex) {
        } catch (RecordStoreNotOpenException ex) {

    // Have to overwrite when we implemtnts RecordComparator
    // Remeber to change the second argument in the enumerateRecords from null to this
    public int compare(byte[] rec1, byte[] rec2) {


        String data1 = new String(rec1);
        String data2 = new String(rec2);

        // Compares two strings lexicographically.
        // The comparison is based on the Unicode value of each character in the strings.
        // We use this to atore the contacts in lexicographically sorting order.
        // Means when you add a new contact it will add to the correct place according to letters of the name.
        int x = data1.compareTo(data2); // Method of String class        

        //  System.out.println(data1);
        //  System.out.println(data2);
        //  System.out.println(x);

        if(x == 0){
            // System.out.println("Equal");
            return RecordComparator.EQUIVALENT;
        }else if(x < 0){
            // System.out.println("Less than");
            return RecordComparator.PRECEDES;
            // System.out.println("Greater than");
            return RecordComparator.FOLLOWS;

        //throw new UnsupportedOperationException("Not supported yet.");

    // Have to overwrite when implements ItemStateListener
    public void itemStateChanged(Item item) {       
        if(item == searchTxtField){
            filterStr = searchTxtField.getString();
            //System.out.println("Item State Changed");

        //throw new UnsupportedOperationException("Not supported yet.");

    // Have to overwrite when implements RecordFilter
    // Remeber to change the first argument in the enumerateRecords from null to this
    public boolean matches(byte[] candidate) {

        //System.out.println("Record Filtering");

        String candi = new String(candidate);

        // Tests if this string starts with the specified prefix.
        // We have initialized the filterStr above with the value ""
        if (candi.startsWith(filterStr)) { // Method os String class
            return true;
        return false;

        //throw new UnsupportedOperationException("Not supported yet.");

Don’t worry about the length of the code sample. Lots of lines aontain comments. I thought it would be better to add comments in the code rather than explaining in the post. Hope you will enjoy this🙂

Lets meet with the part-3. Till then bye😉

About AnujAroshA

An undergraduate in the stream of ICT (Information & Communication Technology). A simple person :)
This entry was posted in J2ME examples. Bookmark the permalink.

7 Responses to Implementing Phone Book application in J2ME (step-2)

  1. Anandkumar S says:

    Thaks for the post. This code was very nice..

  2. LilGob says:

    Since there are not many replies to this i also want to send my warmest appreciation for this! Good Job- it helped me during my Mobile Computing class.

    THANKS from Germany

  3. fihlatv says:

    mr. anujarosha
    thanks for your tutorials. they have helped me a lot. can I ask you an out of scope question?.
    Can you help me implement the push-to-talk Application in mjsip? thank you

  4. John says:

    Hi Anu,

    can you make me application using j2me about clinic system, and include cmd button, text field, next simple page, insert patients data n save..something like that..just a simple one.. coz i want to study about it. Really thank you..

  5. I am not a programmer.
    But I can realize that if mobile’s inbuilt phone book is of 500 entries then one can develop J2ME Application and increase phone book depends on size of memory card.
    do u know any such application ?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s