Code Example

Let's put everything we have covered so far into an example MIDlet and try out a few things. The example below is a simple movie database that uses the serialization technique for saving objects into the record store. It then retrieves them.

package com.javaonpdas.persistence.rms;

import javax.microedition.rms.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
import javax.microedition.io.*;
import java.util.*;

public class RmsMIDlet extends MIDlet
  implements CommandListener, RecordComparator, RecordFilter {

  private Form mainForm = new Form("RmsMIDlet");
  private StringItem resultItem = new StringItem("", "");
  private Command saveCommand = new Command("Save",
    Command.SCREEN, 1);
  private Command getCommand = new Command("Get",
    Command.SCREEN, 1);
  private Command infoCommand = new Command("Info",
    Command.SCREEN, 1);
  private Command deleteCommand = new Command("Delete",
    Command.SCREEN, 1);
  private Command exitCommand = new Command("Exit",
    Command.EXIT, 10);

  private final Movie[] movies = {
    new Movie("The Patriot",
              "Mel Gibson, Heath Ledger, Joely Richardson",
              2000),
    new Movie("Gladiator",
              "Russell Crowe, Joaqin Phoenix, Connie Nielsen",
              2000),
    new Movie("Swordfish",
              "John Travolta, Hugh Jackman",
              2001),
    new Movie("Final Fantasy",
              "Alec Baldwin, Steve Buscemi",
              2001),
    new Movie("The Terminator",
              "Arnold Schwarzenegger, Michael Biehn",
              1984),
    new Movie("The Matrix",
              "Keanu Reeves, Laurence Fishburne",
              1999)};

  public RmsMIDlet() {
    mainForm.append(resultItem);
    mainForm.addCommand(saveCommand);
    mainForm.addCommand(getCommand);
    mainForm.addCommand(infoCommand);
    mainForm.addCommand(deleteCommand);
    mainForm.addCommand(exitCommand);
    mainForm.setCommandListener(this);
  }

  public void startApp() {
    Display.getDisplay (this).setCurrent (mainForm);
  }

  public void pauseApp() {
  }

  public void destroyApp(boolean unconditional) {
  }

  public void commandAction(Command c, Displayable d) {
    RecordStore store = null;
    String recordStoreName = "MyStore";
    try {
      if (c == saveCommand) {
        store = RecordStore.openRecordStore(recordStoreName,
          true);
        for (int i=0; i<movies.length; i++) {
          ByteArrayOutputStream bos =
            new ByteArrayOutputStream();
          DataOutputStream dos = new DataOutputStream(bos);
          // write the object to the stream
          movies[i].writeObject(dos);
          byte[] ba = bos.toByteArray();
          store.addRecord(ba, 0, ba.length);
        }
        store.closeRecordStore();
        resultItem.setLabel ("Status:");
        resultItem.setText(movies.length + " records written");
      }
      else if (c == getCommand) {
        store = RecordStore.openRecordStore(recordStoreName,
          false);
        StringBuffer result = new StringBuffer();
        RecordEnumeration re = store.enumerateRecords(this,
          this, false);
        // RecordEnumeration re = store.enumerateRecords(null,
        //   this, false);
        int i=1;
        while(re.hasNextElement()) {
          ByteArrayInputStream bis = new ByteArrayInputStream(
          re.nextRecord());
          DataInputStream dis = new DataInputStream(bis);
          Movie movie = new Movie();
          movie.readObject(dis);
          result.append(i++ + ": " + movie.title + '\n');
        }
        store.closeRecordStore();
        resultItem.setLabel ("Status:");
        resultItem.setText(result.toString());
      }
      else if (c == infoCommand) {
        store = RecordStore.openRecordStore(recordStoreName,
          false);
        StringBuffer result = new StringBuffer();
        result.append("Name: " + store.getName() + "\n");
        result.append("Records: " + store.getNumRecords() +
          '\n');
        result.append("Store size: " + store.getSize() +
          " bytes\n");
        result.append("Bytes available: " +
          store.getSizeAvailable() + " bytes\n");
        result.append("Version: " + store.getVersion() + "\n");
        resultItem.setLabel("Info:");
        resultItem.setText(result.toString());
      }
      else if (c == deleteCommand) {
        RecordStore.deleteRecordStore(recordStoreName);
        resultItem.setLabel ("Status:");
        resultItem.setText(recordStoreName + " deleted.");
      }
      else if (c == exitCommand) {
        destroyApp(false);
        notifyDestroyed();
      }
    }
    catch (Exception e) {
      e.printStackTrace ();
      resultItem.setLabel ("Error:");
      resultItem.setText (e.toString ());
    }
  }

  public int compare(byte[] rec1, byte[] rec2)
  {
    Movie movie1 = null;
    Movie movie2 = null;
    try {
      ByteArrayInputStream bis1 =
        new ByteArrayInputStream(rec1);
      DataInputStream dis1 = new DataInputStream(bis1);
      movie1 = new Movie();
      movie1.readObject(dis1);
      ByteArrayInputStream bis2 =
        new ByteArrayInputStream(rec2);
      DataInputStream dis2 = new DataInputStream(bis2);
      movie2 = new Movie();
      movie2.readObject(dis2);
    }
    catch (Exception e) {
      System.out.println(e);
      e.printStackTrace();
    }

    // sort by title
    int result = movie1.title.compareTo(movie2.title);
    if (result < 0) {
      return RecordComparator.PRECEDES;
    }
    else if (result > 0) {
      return RecordComparator.FOLLOWS;
    }
    else {
      return RecordComparator.EQUIVALENT;
    }
  }

  public boolean matches(byte[] candidate)
  {
    boolean result = true;
    Movie movie = null;
    try {
      ByteArrayInputStream bis = new ByteArrayInputStream(
        candidate);
      DataInputStream dis = new DataInputStream(bis);
      movie = new Movie();
      movie.readObject(dis);
    }
    catch (Exception e) {
      System.out.println(e);
      e.printStackTrace();
    }
    result = movie.title.startsWith("The");
    return result;
  }
}

Figure 6.1 shows the result when a new database was retrieved and displayed using the Get button (using a null filter).

Figure 6.1. RmsMIDlet

graphics/06fig01.gif

If the filter object is supplied to the enumerateRecords method, it filters out all movies with a title that does not begin with "The". Figure 6.2 shows the display in this case.

Figure 6.2. Record retrieve with filter applied

graphics/06fig02.gif

Figure 6.3 shows the result when the Info button is pressed. Note that the getVersion method returns 25, which is a number that increases for each record that is added, modified, or deleted. It is a useful way to tell whether a record store has changed. Note though that the initial version number is implementation-dependent and is not necessarily zero.

Figure 6.3. RMS database information displayed

graphics/06fig03.gif