Dhafiq Sagara adalah orang bodoh yang tidak bisa apa-apa, tapi dia selalu berusaha untuk terus menjadi yang lebih baik. Rasa keingin-tahuannya sangat tinggi, selalu berusaha dan terus berusaha, trial dan error adalah prinsip belajarnya.

17 Mei 2011

RMS Phonebook Pada J2ME

RMS (Record Management System) adalah kumpulan catatan, dan catatan tersebut yang disimpan sebagai array dari byte dalam sebuah record store. RMS memiliki orientasi record simple database, sehingga MIDlet dapat menyimpan informasi dan mengaksesnya. Pada konsep, sebuah record yang disimpan pada record store diakses berdasarkan integer recordID. RecordID biasanya digunakan untuk mengakses sebuah record sebagai fungsi untuk mengakses indeks dalam array.

Saya ingin berbagi sebuah program sederhana RMS Phonebook. Sebuah aplikasi J2ME yang sudah support CRUD (Create Read Update Delete) kontak di buku telepon menggunakan RMS. Dalam program ini, kita dapat menyimpan kontak, memperbarui kontak, menghapus kontak, dan menemukan kontak di record store. Dalam tutorial ini, saya menggunakan Netbeans untuk membuat aplikasinya.

  1. Buatlah sebuah project J2ME pada Netbeans anda.
  2. Buatlah sebuah class baru dan beri nama Comparator. Kemudian masukkan code berikut:
    Comparator.java
    import java.io.*;
    import javax.microedition.rms.RecordComparator;
    
    public class Comparator implements RecordComparator {
    
        private byte[] comparatorInputData = new byte[300];
        private ByteArrayInputStream comparatorInputStream = null;
        private DataInputStream comparatorInputDataType = null;
    
        public int compare(byte[] record1, byte[] record2) {
            int record1int, record2int;
            try {
                comparatorInputStream = new ByteArrayInputStream(record1);
                comparatorInputDataType = new DataInputStream(comparatorInputStream);
                String data1 = comparatorInputDataType.readUTF();
                comparatorInputStream = new ByteArrayInputStream(record2);
                comparatorInputDataType = new DataInputStream(comparatorInputStream);
                String data2 = comparatorInputDataType.readUTF();
                int comparison = data1.compareTo(data2);
                if (comparison == 0) {
                    return RecordComparator.EQUIVALENT;
                } else if (comparison < 0) {
                    return RecordComparator.PRECEDES;
                } else {
                    return RecordComparator.FOLLOWS;
                }
            } catch (Exception error) {
                return RecordComparator.EQUIVALENT;
            }
        }
    
        public void compareClose() {
            try {
                if (comparatorInputStream != null) {
                    comparatorInputStream.close();
                }
                if (comparatorInputDataType != null) {
                    comparatorInputDataType.close();
                }
            } catch (Exception error) {
            }
        }
    }
  3. Kemudian buat class baru lagi dan beri nama Filter. Class ini digunakan untuk proses mem-filter pencarian kontak. Fungsi pencarian ini dapat menggunakan satu atau lebih keyword kata. Berikut ini kode untuk Filter.java:
    import java.io.ByteArrayInputStream;
    import java.io.DataInputStream;
    import javax.microedition.rms.RecordFilter;
    
    public class Filter implements RecordFilter {
    
        private String search = null;
        private ByteArrayInputStream inputstream = null;
        private DataInputStream datainputstream = null;
    
        public Filter(String search) {
            this.search = search.toLowerCase();
        }
    
        public boolean matches(byte[] suspect) {
            String string = new String(suspect).toLowerCase();
            if (string != null && string.indexOf(search) != -1) {
                return true;
            } else {
                return false;
            }
        }
    
        public void filterClose() {
            try {
                if (inputstream != null) {
                    inputstream.close();
                }
                if (datainputstream != null) {
                    datainputstream.close();
                }
            } catch (Exception error) {
            }
        }
    }
    
  4. Tahap terakhir, buatlah sebuah MIDlet baru dan beri nama RMSPhonebook. Berikut codenya:
    import javax.microedition.rms.*;
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import java.io.*;
    
    public class RMSPhonebook extends MIDlet implements CommandListener {
    
        private Display display;
        private Alert alert;
        private Form formMain, formNewContact, formView, formEdit, formSearch;
        private List list;
        private RecordStore recordstore = null;
        private RecordEnumeration recordEnumeration = null;
        private Filter filter = null;
    
        Command cmdExit = new Command("Exit", Command.EXIT, 1);
        Command cmdViewList = new Command("Contacts", Command.SCREEN, 1);
        Command cmdNewContact = new Command("Add New Contact", Command.SCREEN, 1);
        Command cmdEdit = new Command("Edit Contact", Command.SCREEN, 1);
        Command cmdDelete = new Command("Delete Contact", Command.SCREEN, 1);
        Command cmdFind = new Command("Find Contact", Command.SCREEN, 1);
        Command cmdSearch = new Command("Search", Command.SCREEN, 1);
        Command cmdSave = new Command("Save", Command.SCREEN, 1);
        Command cmdUpdate = new Command("Update", Command.SCREEN, 1);
        Command cmdCancel = new Command("Cancel", Command.BACK, 1);
        Command cmdBack = new Command("Back", Command.BACK, 1);
    
        TextField txtName = new TextField("Name:", "", 20, TextField.ANY);
        TextField txtAddress = new TextField("Address:", "", 20, TextField.ANY);
        TextField txtHomeNumber = new TextField("Home Number:", "", 20, TextField.PHONENUMBER);
        TextField txtMobileNumber = new TextField("Mobile Number:", "", 20, TextField.PHONENUMBER);
        TextField txtRecName, txtRecAddress, txtRecHomeNumber, txtRecMobileNumber;
        TextField txtFind = new TextField("Search Contact:", "", 20, TextField.ANY);
    
        int recID, currentTask;
        String keyword;
    
        public RMSPhonebook() {
            formMain = new Form("RMS Phonebook");
            try {
                Image img = Image.createImage("/dhafiqsagara.png");
                ImageItem image = new ImageItem("\n\n\n\n", img, Item.LAYOUT_CENTER, "List Phonebook");
                formMain.append(image);
            } catch (Exception e) {
                e.printStackTrace();
            }
            formMain.addCommand(cmdViewList);
            formMain.addCommand(cmdExit);
            formMain.setCommandListener(this);
    
            //Add New Form
            formNewContact = new Form("Add New Contact");
            formNewContact.addCommand(cmdBack);
            formNewContact.addCommand(cmdSave);
            formNewContact.append(txtName);
            formNewContact.append(txtAddress);
            formNewContact.append(txtHomeNumber);
            formNewContact.append(txtMobileNumber);
            formNewContact.setCommandListener(this);
    
            formSearch = new Form("Search Name of Phonebook");
            formSearch.addCommand(cmdBack);
            formSearch.addCommand(cmdSearch);
            formSearch.append(txtFind);
            formSearch.setCommandListener(this);
        }
    
        public void startApp() {
            if (display == null) {
                display = Display.getDisplay(this);
                display.setCurrent(formMain);
            }
        }
    
        public void pauseApp() {
        }
    
        public void destroyApp(boolean unconditional) {
        }
    
        public void commandAction(Command c, Displayable d) {
            //trying to open a RecordStore if existing, and if not create it
            try {
                recordstore = RecordStore.openRecordStore("phonebookRS", true);
            } catch (Exception error) {
                alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
    
            //for exit command, just destroying the applications
        if (c == cmdExit) {
                destroyApp(true);
                notifyDestroyed();
            }
    
            //for back command, setting display to the mainForm
            if (c == cmdBack) {
                display.setCurrent(list);
            }
    
            //for cancel command, setting display to the mainForm
            if (c == cmdCancel) {
                display.setCurrent(formMain);
            }
    
            //for displaying new contact form
            if (c == cmdNewContact) {
                txtName.setString("");
                txtAddress.setString("");
                txtHomeNumber.setString("");
                txtMobileNumber.setString("");
                display.setCurrent(formNewContact);
            }
    
            //for displaying search form
            if (c == cmdFind) {
                txtFind.setString("");
                display.setCurrent(formSearch);
            }
    
            //for searching
            if (c == cmdSearch) {
                keyword = txtFind.getString();
                try {
                    list = new List("List Phonebook", List.IMPLICIT);
                    list.addCommand(cmdNewContact);
                    list.addCommand(cmdFind);
                    list.addCommand(cmdCancel);
                    list.setCommandListener(this);
                    currentTask = 1;
                    String inputName = null;
                    byte[] byteInputData = new byte[300];
                    ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
                    DataInputStream inputDataStream = new DataInputStream(inputStream);
                    if (recordstore.getNumRecords() > 0) {
                        filter = new Filter(keyword);
                        recordEnumeration = recordstore.enumerateRecords(filter, null, false);
                        while (recordEnumeration.hasNextElement()) {
                            recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                            inputName = inputDataStream.readUTF();
                            list.append(inputName + "", null);
                            inputStream.reset();
                        }
                    }
                    display.setCurrent(list);
                    inputStream.close();
                } catch (Exception error) {
                    alert = new Alert("Error Reading",
                            error.toString(), null, AlertType.WARNING);
                    alert.setTimeout(Alert.FOREVER);
                    display.setCurrent(alert);
                }
            }
    
            //for saving new contact
            if (c == cmdSave) {
                try {
                    String outputName = txtName.getString();
                    String outputAddress = txtAddress.getString();
                    String outputHomeNumber = txtHomeNumber.getString();
                    String outputMobileNumber = txtMobileNumber.getString();
                    byte[] outputRecord;
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    DataOutputStream outputDataStream = new DataOutputStream(outputStream);
                    outputDataStream.writeUTF(outputName);
                    outputDataStream.writeUTF(outputAddress);
                    outputDataStream.writeUTF(outputHomeNumber);
                    outputDataStream.writeUTF(outputMobileNumber);
                    outputDataStream.flush();
                    outputRecord = outputStream.toByteArray();
                    recordstore.addRecord(outputRecord, 0, outputRecord.length);
                    outputStream.reset();
                    outputStream.close();
                    outputDataStream.close();
                    display.setCurrent(formMain);
                } catch (Exception error) {
                    display.setCurrent(alert);
                }
            }
    
            //for updating contact entries
            if (c == cmdUpdate) {
                try {
                    String outputName = txtRecName.getString();
                    String outputAddress = txtRecAddress.getString();
                    String outputHomeNumber = txtRecHomeNumber.getString();
                    String outputMobileNumber = txtRecMobileNumber.getString();
                    byte[] outputRecord;
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    DataOutputStream outputDataStream = new DataOutputStream(outputStream);
                    outputDataStream.writeUTF(outputName);
                    outputDataStream.writeUTF(outputAddress);
                    outputDataStream.writeUTF(outputHomeNumber);
                    outputDataStream.writeUTF(outputMobileNumber);
                    outputDataStream.flush();
                    outputRecord = outputStream.toByteArray();
                    recordstore.setRecord(recID, outputRecord, 0, outputRecord.length);
                    outputStream.reset();
                    outputStream.close();
                    outputDataStream.close();
                    display.setCurrent(formMain);
                } catch (Exception error) {
                    alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING);
                    alert.setTimeout(Alert.FOREVER);
                    display.setCurrent(alert);
                }
            }
    
            //for editing contact
            if (c == cmdEdit) {
                int index = 1 + list.getSelectedIndex();
                try {
                    formEdit = new Form("Edit Contact Details");
                    formEdit.addCommand(cmdBack);
                    formEdit.addCommand(cmdUpdate);
                    formEdit.setCommandListener(this);
                    byte[] byteInputData = new byte[300];
                    String inputName, inputAddress, inputHomeNumber, inputMobileNumber = null;
                    ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
                    DataInputStream inputDataStream = new DataInputStream(inputStream);
                    if (currentTask == 1) {
                        filter = new Filter(keyword);
                        recordEnumeration = recordstore.enumerateRecords(filter, null, false);
                    }
                    if (currentTask == 2) {
                        Comparator comparator = new Comparator();
                        recordEnumeration = recordstore.enumerateRecords(null, comparator, false);
                    }
                    for (int i = 1; i <= recordEnumeration.numRecords(); i++) {
                        int datapointer = recordEnumeration.nextRecordId();
                        if (i == index) {
                            recordstore.getRecord(datapointer, byteInputData, 0);
                            recID = datapointer;
                            inputName = inputDataStream.readUTF();
                            inputAddress = inputDataStream.readUTF();
                            inputHomeNumber = inputDataStream.readUTF();
                            inputMobileNumber = inputDataStream.readUTF();
                            txtRecName = new TextField("Name:", inputName, 20, TextField.ANY);
                            txtRecAddress = new TextField("Address:", inputAddress, 20, TextField.ANY);
                            txtRecHomeNumber = new TextField("Home Number:", inputHomeNumber, 20, TextField.PHONENUMBER);
                            txtRecMobileNumber = new TextField("Mobile Number:", inputMobileNumber, 20, TextField.PHONENUMBER);
    
                            formEdit.append(txtRecName);
                            formEdit.append(txtRecAddress);
                            formEdit.append(txtRecHomeNumber);
                            formEdit.append(txtRecMobileNumber);
                            inputStream.reset();
                        }
                    }
                    display.setCurrent(formEdit);
                    inputStream.close();
                } catch (Exception error) {
                    alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING);
                    alert.setTimeout(Alert.FOREVER);
                    display.setCurrent(alert);
                }
            }
    
            if (c == cmdDelete) {
                int index = 1 + list.getSelectedIndex();
                try {
                    if (currentTask == 1) {
                        filter = new Filter(keyword);
                        recordEnumeration = recordstore.enumerateRecords(filter, null, false);
                    }
                    if (currentTask == 2) {
                        Comparator comparator = new Comparator();
                        recordEnumeration = recordstore.enumerateRecords(null, comparator, false);
                    }
                    for (int i = 1; i <= recordEnumeration.numRecords(); i++) {
                        int datapointer = recordEnumeration.nextRecordId();
                        if (i == index) {
                            recordstore.deleteRecord(datapointer);
                        }
                    }
                    display.setCurrent(formMain);
                } catch (Exception error) {
                    alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING);
                    alert.setTimeout(Alert.FOREVER);
                    display.setCurrent(alert);
                }
            }
    
            if (c == cmdViewList) {
                try {
                    list = new List("List Phonebook", List.IMPLICIT);
                    list.addCommand(cmdNewContact);
                    list.addCommand(cmdFind);
                    list.addCommand(cmdCancel);
                    list.setCommandListener(this);
                    currentTask = 2;
                    byte[] byteInputData = new byte[300];
                    String inputName, inputAddress, inputHomeNumber, inputMobileNumber = null;
                    ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
                    DataInputStream inputDataStream = new DataInputStream(inputStream);
                    Comparator comparator = new Comparator();
                    recordEnumeration = recordstore.enumerateRecords(null, comparator, false);
                    while (recordEnumeration.hasNextElement()) {
                        recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                        inputName = inputDataStream.readUTF();
                        inputAddress = inputDataStream.readUTF();
                        inputHomeNumber = inputDataStream.readUTF();
                        inputMobileNumber = inputDataStream.readUTF();
                        list.append(inputName + "", null);
                        inputStream.reset();
                    }
                    display.setCurrent(list);
                    inputStream.close();
                } catch (Exception error) {
                    alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING);
                    alert.setTimeout(Alert.FOREVER);
                    display.setCurrent(alert);
                }
            }
    
            //for viewing each contact using the SELECT_COMMAND
            if (c == List.SELECT_COMMAND) {
                int index = 1 + list.getSelectedIndex();
                try {
                    formView = new Form("Contact Details");
                    formView.addCommand(cmdBack);
                    formView.addCommand(cmdEdit);
                    formView.addCommand(cmdDelete);
                    formView.setCommandListener(this);
                    byte[] byteInputData = new byte[300];
                    String inputName, inputAddress, inputHomeNumber, inputMobileNumber = null;
                    ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
                    DataInputStream inputDataStream = new DataInputStream(inputStream);
                    if (currentTask == 1) {
                        filter = new Filter(keyword);
                        recordEnumeration = recordstore.enumerateRecords(filter, null, false);
                    }
                    if (currentTask == 2) {
                        Comparator comparator = new Comparator();
                        recordEnumeration = recordstore.enumerateRecords(null, comparator, false);
                    }
                    for (int i = 1; i <= recordEnumeration.numRecords(); i++) {
                        int datapointer = recordEnumeration.nextRecordId();
                        if (i == index) {
                            recordstore.getRecord(datapointer, byteInputData, 0);
                            recID = datapointer;
                            inputName = inputDataStream.readUTF();
                            inputAddress = inputDataStream.readUTF();
                            inputHomeNumber = inputDataStream.readUTF();
                            inputMobileNumber = inputDataStream.readUTF();
                            StringItem stringName = new StringItem("Name: ", inputName, Item.PLAIN);
                            StringItem stringAddress = new StringItem("Address: ", inputAddress, Item.PLAIN);
                            StringItem stringHomeNumber = new StringItem("Home Number: ", inputHomeNumber, Item.PLAIN);
                            StringItem stringMobileNumber = new StringItem("Mobile Number: ", inputMobileNumber, Item.PLAIN);
                            formView.append(stringName);
                            formView.append(stringAddress);
                            formView.append(stringHomeNumber);
                            formView.append(stringMobileNumber);
                            inputStream.reset();
                        }
                    }
                    display.setCurrent(formView);
                    inputStream.close();
                } catch (Exception error) {
                    alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING);
                    alert.setTimeout(Alert.FOREVER);
                    display.setCurrent(alert);
                }
            }
    
            try {
                recordstore.closeRecordStore();
            } catch (Exception error) {
                alert = new Alert("Error Closing", error.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
        }
    }
    

Silahkan download project RMSPhonebook.zip.

11 komentar:

  1. makasih mas admin buat infonya. saya mau nanya, saya kan mau membuat aplikasi j2me kamus. itu gmana ya mas? kalo pake rms gmana ya? mhon balasannya, thx :)

    BalasHapus
  2. bisa juga kok bikin kamus yg datanya disimpan RMS

    BalasHapus
  3. Terima Kasih Source Code nya...
    aku akan daftarkan di DAFTAR PUSTAKA saya...

    BalasHapus
  4. wah...Bermanfaat ?

    BalasHapus
  5. wahhh.. terima kasih agan admin :D
    saja jadi tahu fungsi Database RMS..

    BalasHapus
  6. TERIMA KASIH BANYAK GAN ATAS BANTUAN NYA
    SUNGGUH ARTIKEL YANG BERMANFAAT DAN SUKSES !!!!!!

    BalasHapus
  7. aaaaaaaaaaa banyak error give me a clue..
    di netbeans 7.1 ga bisa??
    lagi ga ada netbeans 6.1 >.<

    BalasHapus
  8. Bang kalau cara buat kamus dengan database rms gimana....???\
    kalau ada source codenya minta dong, saya mau pelajari...
    thank's before...
    ^_^

    BalasHapus
  9. Simple dan bermanfaat, makasih gan :)

    BalasHapus
  10. bang, source codenya gk bbisa di download, upload di 4shared dong.

    BalasHapus