Bab Persistence, Penyimpanan data aplikasi dalam local device

Mari berbagi. Kali ini saya menulis sebagain contoh dari pembuatan aplikasi mobile dengan menggunakan API MIDP Record Management System yang sudah disediakan oleh MIDlets. Sebagai pengantar sebelum proses pembuatan aplikasi saya jelaskan sedikit mengenai Record Management System, MIDP menyediakan sebuah API dimana program dapat menyimpan data-data aplikasi secara lokal didalam device tersebut. MIDP Record Management System adalah sebuah fasilitas yang dimiliki oleh MIDlets untuk menyimpan data-data aplikasi pada saat MIDlet invocations. Data akan disimpan dalam non-volatile memory didalam device. Hal ini berarti, data-data program yang telah disimpan tidak akan hilang walaupun program di restart maupun device dimatikan.

 

Baik langsung saja, saya membuat aplikasi mobile mengenaik catatan belanja, langkah-langkah nya sebagai berikut:

Setelah membuat project java mobile, sekarang membuat file midlet. Buat file midlet dengan nama KeluarUang, lalu ketikan code sebagai berikut:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
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.Image;
import javax.microedition.lcdui.ImageItem;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.List;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.lcdui.Ticker;
import javax.microedition.midlet.*;
import javax.microedition.rms.RecordComparator;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;

/**
 * @author ricky juniar iskandar - 1142045
 */
public class KeluarUang extends MIDlet implements CommandListener{
    Display display;
    Alert alert;
    Form formAbout, formUtama, formTambahData, formLihat, formEdit, formHelp;
    List list;
    RecordStore recordstore = null;
    RecordEnumeration recordEnumeration = null;
    Ticker tik;
    Command cmdAbout = new Command("Tentang Aplikasi", Command.OK, 3);
    Command cmdHelp = new Command("Petunjuk Aplikasi", Command.OK, 2);
    Command cmdKeluar = new Command("Keluar", Command.EXIT, 1);
    Command cmdLihatData = new Command("Lihat Data", Command.SCREEN, 1);
    Command cmdDataBaru = new Command("Tambah", Command.SCREEN, 1);
    Command cmdEdit = new Command("Edit Data", Command.SCREEN, 1);
    Command cmdHapus = new Command("Hapus Data", Command.SCREEN, 1);
    Command cmdSimpan = new Command("Simpan", Command.SCREEN, 1);
    Command cmdUbah = new Command("Edit", Command.SCREEN, 1);
    Command cmdCancel = new Command("Kembali", Command.BACK, 1);
    Command cmdBack = new Command("Kembali", Command.BACK, 1);
    Command cmdKembali = new Command("Kembali", Command.BACK, 1);
    TextField txtNama = new TextField("Nama Pengeluaran:", "", 30, TextField.ANY);
    TextField txtTgl = new TextField("Tanggal:", "", 15, TextField.ANY);
    TextField txtJml = new TextField("Jumlah Pengeluaran:", "", 20, TextField.NUMERIC);
    TextField txtRecNama, txtRecTgl, txtRecJml;
    int recID, currentTask;
    
    public KeluarUang(){
        tik = new Ticker("Aplikasi Buku Pengeluaran Ku");
        
        // form utama
        formUtama = new Form("");
        try {
            Image img = Image.createImage("/bukupengeluaranku.png");
            ImageItem image = new ImageItem("", img, Item.LAYOUT_CENTER, "Data Karyawan");
            formUtama.append(image);
        } catch (Exception e) {
            e.printStackTrace();
        }
        formUtama.addCommand(cmdLihatData);
        formUtama.addCommand(cmdKeluar);
        formUtama.addCommand(cmdAbout);
        formUtama.addCommand(cmdHelp);
        formUtama.setCommandListener(this);
        
        // form tambah data
        formTambahData = new Form("Tambah Data Pengeluaran");
        formTambahData.addCommand(cmdBack);
        formTambahData.addCommand(cmdSimpan);
        formTambahData.append(txtNama);
        formTambahData.append(txtTgl);
        formTambahData.append(txtJml);
        formTambahData.setTicker(tik);
        formTambahData.setCommandListener(this);
        
        // form about
        formAbout = new Form("Tentang Aplikasi");
        formAbout.append("Aplikasi Buku Pengeluaran Ku adalah aplikasi yang berjalan pada handphone berbasis java."
                + " Aplikasi ini dapat membantu anda untuk menyimpan informasi pengeluaran uang"
                + " yang anda lakukan, dengan aplikasi ini anda tidak perlu menggunkan buku sebagai"
                + " media mencatat, tinggal keluarkan handphone anda semua masalah dapat terselesaikan.\n"
                + "Dibuat oleh: Ricky Juniar Iskandar - NPM: 1142045");
        formAbout.addCommand(cmdKembali);
        formAbout.setTicker(tik);
        formAbout.setCommandListener(this);
        
        // form help
        formHelp = new Form("Petunjuk Aplikasi");
        formHelp.append("- Menyimpan Data Pengeluaran:(1) Pilih Menu (2) Pilih Lihat Data"
                + " (3) Pilih Tambah (4) Isi form tambah pengeluaran"
                + " (5) Setelah itu pilih menu (6) Pilih simpan\n"
                + "-Edit Data Pengeluaran: (1) Pilih Menu (2) Pilih Lihat Data"
                + " (3) Pilih data yang akan di edit (4) Tekan tombol tengah"
                + " (5) Pilih Menu (6) Tekan Edit Data (7) Isi form edit data pengeluaran"
                + " (8) Setelah itu pilih menu (9) Pilih Edit\n"
                + "-Hapus Data Pengeluaran: (1) Pilih Menu (2) Pilih Lihat Data"
                + " (3) Pilih data yang akan di edit (4) Tekan tombol tengah"
                + " (5) Pilih Menu (6) Tekan Hapus Data");
        formHelp.setTicker(tik);
        formHelp.addCommand(cmdKembali);
        formHelp.setCommandListener(this);
        
    }
    
    //untuk menghitung dan membandingkan jumlah recod daman rms
    public class RmsBanding 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) {
            }
        }
    }
    
    public void listData(){
        try {
            list = new List("Data Pengeluaran", List.IMPLICIT);
            list.addCommand(cmdDataBaru);
            list.addCommand(cmdCancel);
            list.setTicker(tik);
            list.setCommandListener(this);
            currentTask = 2;
            byte[] byteInputData = new byte[300];
            String inputNama, inputTgl, inputJml = null;
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            KeluarUang.RmsBanding comparator = new KeluarUang.RmsBanding();
            recordEnumeration = recordstore.enumerateRecords(null, comparator, false);
            while (recordEnumeration.hasNextElement()) {
                recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                inputNama = inputDataStream.readUTF();
                inputTgl = inputDataStream.readUTF();
                inputJml = inputDataStream.readUTF();

                list.append(inputNama + " : Rp. " + inputJml + "", 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);
        }
    }

    public void startApp() {
        if (display == null) {
            display = Display.getDisplay(this);
            display.setCurrent(formUtama);
        }
    }
    
    public void pauseApp() {
    }
    
    public void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command c, Displayable d) {
        try {
            recordstore = RecordStore.openRecordStore("BukuPengeluaranKu", true);
        } catch (Exception error) {
            alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }


        if (c == cmdKeluar) {
            destroyApp(true);
            notifyDestroyed();
        }


        if (c == cmdBack) {
            display.setCurrent(list);
        }


        if (c == cmdCancel) {
            display.setCurrent(formUtama);
        }

        if (c == cmdAbout) {
            display.setCurrent(formAbout);
        }

        if (c == cmdHelp) {
            display.setCurrent(formHelp);
        }

        if (c == cmdKembali) {
            display.setCurrent(formUtama);
        }


        if (c == cmdDataBaru) {
            txtNama.setString("");
            txtTgl.setString("");
            txtJml.setString("");
            display.setCurrent(formTambahData);
        }


        if (c == cmdSimpan) {
            try {
                String outputNama = txtNama.getString();
                String outputTgl = txtTgl.getString();
                String outputJml = txtJml.getString();
                byte[] outputRecord;
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                DataOutputStream outputDataStream = new DataOutputStream(outputStream);
                outputDataStream.writeUTF(outputNama);
                outputDataStream.writeUTF(outputTgl);
                outputDataStream.writeUTF(outputJml);
                outputDataStream.flush();
                outputRecord = outputStream.toByteArray();
                recordstore.addRecord(outputRecord, 0, outputRecord.length);
                outputStream.reset();
                outputStream.close();
                outputDataStream.close();
                listData();
            } catch (Exception error) {
                display.setCurrent(alert);
            }
        }


        if (c == cmdEdit) {
            int index = 1 + list.getSelectedIndex();
            try {
                formEdit = new Form("Ubah data pengeluaran");
                formEdit.addCommand(cmdBack);
                formEdit.addCommand(cmdUbah);
                formEdit.setCommandListener(this);
                byte[] byteInputData = new byte[300];
                String inputNama, inputTgl, inputJml = null;
                ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
                DataInputStream inputDataStream = new DataInputStream(inputStream);

                if (currentTask == 2) {
                    KeluarUang.RmsBanding comparator = new KeluarUang.RmsBanding();
                    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;
                        inputNama = inputDataStream.readUTF();
                        inputTgl = inputDataStream.readUTF();
                        inputJml = inputDataStream.readUTF();
                        txtRecNama = new TextField("Nama Pengeluaran:", inputNama, 30, TextField.ANY);
                        txtRecTgl = new TextField("Tanggal\t:", inputTgl, 15, TextField.ANY);
                        txtRecJml = new TextField("Jumlah\t:", inputJml, 20, TextField.NUMERIC);
                        
                        formEdit.append(txtRecNama);
                        formEdit.append(txtRecTgl);
                        formEdit.append(txtRecJml);
                        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 == cmdUbah) {
            try {
                String outputNama = txtRecNama.getString();
                String outputTgl = txtRecTgl.getString();
                String outputJml = txtRecJml.getString();
                byte[] outputRecord;
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                DataOutputStream outputDataStream = new DataOutputStream(outputStream);
                outputDataStream.writeUTF(outputNama);
                outputDataStream.writeUTF(outputTgl);
                outputDataStream.writeUTF(outputJml);
                outputDataStream.flush();
                outputRecord = outputStream.toByteArray();
                recordstore.setRecord(recID, outputRecord, 0, outputRecord.length);
                outputStream.reset();
                outputStream.close();
                outputDataStream.close();
                listData();
            } catch (Exception error) {
                alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
        }

        if (c == cmdHapus) {
            int index = 1 + list.getSelectedIndex();
            try {

                if (currentTask == 2) {
                    KeluarUang.RmsBanding comparator = new KeluarUang.RmsBanding();
                    recordEnumeration = recordstore.enumerateRecords(null, comparator, false);
                }
                for (int i = 1; i <= recordEnumeration.numRecords(); i++) {
                    int datapointer = recordEnumeration.nextRecordId();
                    if (i == index) {
                        recordstore.deleteRecord(datapointer);
                    }
                }
                listData();
            } catch (Exception error) {
                alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
        }

        if (c == cmdLihatData) {
            listData();
        }


        if (c == List.SELECT_COMMAND) {
            int index = 1 + list.getSelectedIndex();
            try {
                formLihat = new Form("Data Pengeluaran : ");
                formLihat.addCommand(cmdBack);
                formLihat.addCommand(cmdEdit);
                formLihat.addCommand(cmdHapus);
                formLihat.setCommandListener(this);
                byte[] byteInputData = new byte[300];
                String inputNama, inputTgl, inputJml = null;
                ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
                DataInputStream inputDataStream = new DataInputStream(inputStream);

                if (currentTask == 2) {
                    KeluarUang.RmsBanding comparator = new KeluarUang.RmsBanding();
                    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;
                        inputNama = inputDataStream.readUTF();
                        inputTgl = inputDataStream.readUTF();
                        inputJml = inputDataStream.readUTF();
                        StringItem stringNama = new StringItem("Nama Pengeluaran: ", inputNama, Item.PLAIN);
                        StringItem stringTgl = new StringItem("Tanggal\t: ", inputTgl, Item.PLAIN);
                        StringItem stringJml = new StringItem("Jumlah\t: ", inputJml, Item.PLAIN);
                        formLihat.append(stringNama);
                        formLihat.append(stringTgl);
                        formLihat.append(stringJml);
                        inputStream.reset();
                    }
                }
                display.setCurrent(formLihat);
                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);
        }
    }
}

Atau anda dapat mendownload nya file midle dan gambar. Disini: Download Midlet Download Gambar. Hasilnya dapat dilihat sebagai beriku:

Screen Shot 2013 03 12 at 6 00 47 PMScreen Shot 2013 03 12 at 6 00 57 PMScreen Shot 2013 03 12 at 6 01 32 PM

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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