RMS in j2me

Chapter 6 - MIDP Persistent Storage

    RMS in j2me

  • Persistent Storage

              The MIDP provides a MIDlets to persistently store data and retrieve it later. This persistent storage mechanism called the Record Management System (RMS).It  is a simple record-oriented database.

    Record Store

              A record store consists of a collection of records that its remain persistent across multiple records of a MIDlet.

              It is responsible for maintain the integrity of the MIDlets record stores throughout the normal use of the platform, including reboots, battery changes.

              MIDlets within a MIDlet suite are allowed to create multiple record stores, as long as they are each given different names.Record stores are created in platform-dependent locations.

              MIDlets within a MIDlet suite can access one another's record stores directly.Access controls are defined when RecordStores to be shared are created.

              Access controls are enforced when RecordStores are opened. The access modes allow private use or shareable with any other MIDlet.

              Record store names are case sensitive and may consist of any combination of up to 32 Unicode characters. Record store names MUST be unique within the scope of a given MIDlet.

              A MIDlet in one MIDlet suite is allowed to have a record store with the same name as a MIDlet in another MIDlet suite.

              Record store implementations ensure that all individual record store operations are atomic, synchronous, and serialized so that no corruption occurs with multiple accesses.

              This record store API uses long integers for time/date stamps, in the format used by System.currentTimeMillis() . The record store is time stamped with the last time it was modified.


    Records

              Records are arrays of bytes.Use DataInputStream,DataOutputStream ,ByteArrayInputStream and ByteArrayOutputStream to pack and unpack different data types into and out of the byte arrays.

              Records are uniquely identified within a given record store by their recordId , which is an integer value. This recordId is used as the primary key for the records.

              The first record created in a record store will have recordId equal to 1, and each subsequent recordId will monotonically increase by one.

    Example:

              The example uses the Record Management System to store and retrieve high scores for a game.


    import javax.microedition.rms.*;
    import java.io.DataOutputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.ByteArrayInputStream;
    import java.io.DataInputStream;
    import java.io.EOFException;

    /**
     * A class used for storing and showing game scores.
     */
    public class RMSGameScores
        implements RecordFilter, RecordComparator
    {
        /*
         * The RecordStore used for storing the game scores.
         */
        private RecordStore recordStore = null;

        /*
         * The player name to use when filtering.
         */
        public static String playerNameFilter = null;

        /*
         * Part of the RecordFilter interface.
         */
        public boolean matches(byte[] candidate)
     throws IllegalArgumentException
        {
     // If no filter set, nothing can match it.
     if (this.playerNameFilter == null) {
         return false;
     }

     ByteArrayInputStream bais = new ByteArrayInputStream(candidate);
     DataInputStream inputStream = new DataInputStream(bais);
     String name = null;
     
     try {
         int score = inputStream.readInt();
         name = inputStream.readUTF();
     }
     catch (EOFException eofe) {
         System.out.println(eofe);
         eofe.printStackTrace();
     }
     catch (IOException eofe) {
         System.out.println(eofe);
         eofe.printStackTrace();
     }
     return (this.playerNameFilter.equals(name));
        }

        /*
         * Part of the RecordComparator interface.
         */
        public int compare(byte[] rec1, byte[] rec2)
        {
     // Construct DataInputStreams for extracting the scores from
     // the records.
     ByteArrayInputStream bais1 = new ByteArrayInputStream(rec1);
     DataInputStream inputStream1 = new DataInputStream(bais1);
     ByteArrayInputStream bais2 = new ByteArrayInputStream(rec2);
     DataInputStream inputStream2 = new DataInputStream(bais2);
     int score1 = 0;
     int score2 = 0;
     try {
         // Extract the scores.
         score1 = inputStream1.readInt();
         score2 = inputStream2.readInt();
     }
     catch (EOFException eofe) {
         System.out.println(eofe);
         eofe.printStackTrace();
     }
     catch (IOException eofe) {
         System.out.println(eofe);
         eofe.printStackTrace();
     }

     // Sort by score
     if (score1 < score2) {
         return RecordComparator.PRECEDES;
     }
     else if (score1 > score2) {
         return RecordComparator.FOLLOWS;
     }
     else {
         return RecordComparator.EQUIVALENT;
     }
        }

        /**
         * The constructor opens the underlying record store,
         * creating it if necessary.
         */
        public RMSGameScores()
        {
     //
     // Create a new record store for this example
     //
     try {
         recordStore = RecordStore.openRecordStore("scores", true);
     }
     catch (RecordStoreException rse) {
         System.out.println(rse);
         rse.printStackTrace();
     }
        }

        /**
         * Add a new score to the storage.
         *
         * @param score the score to store.
         * @param playerName the name of the play achieving this score.
         */
        public void addScore(int score, String playerName)
        {
     //
     // Each score is stored in a separate record, formatted with
     // the score, followed by the player name.
     //
            int recId;  // returned by addRecord but not used
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     DataOutputStream outputStream = new DataOutputStream(baos);
     try {
         // Push the score into a byte array.
         outputStream.writeInt(score);
         // Then push the player name.
         outputStream.writeUTF(playerName);
     }
     catch (IOException ioe) {
         System.out.println(ioe);
         ioe.printStackTrace();
     }

     // Extract the byte array
     byte[] b = baos.toByteArray();
     // Add it to the record store
     try {
         recId = recordStore.addRecord(b, 0, b.length);
     }
     catch (RecordStoreException rse) {
         System.out.println(rse);
         rse.printStackTrace();
     }
        }

        /**
         * A helper method for the printScores methods.
         */
        private void printScoresHelper(RecordEnumeration re)
        {
     try {
         while(re.hasNextElement()) {
      int id = re.nextRecordId();
      ByteArrayInputStream bais = new ByteArrayInputStream(recordStore.getRecord(id));
      DataInputStream inputStream = new DataInputStream(bais);
      try {
          int score = inputStream.readInt();
          String playerName = inputStream.readUTF();
          System.out.println(playerName + " = " + score);
      }
      catch (EOFException eofe) {
          System.out.println(eofe);
          eofe.printStackTrace();
      }
         }
     }
     catch (RecordStoreException rse) {
         System.out.println(rse);
         rse.printStackTrace();
     }
     catch (IOException ioe) {
         System.out.println(ioe);
         ioe.printStackTrace();
     }
        }

        /**
         * This method prints all of the scores sorted by game score.
         */
        public void printScores()
        {
     try {
         // Enumerate the records using the comparator implemented
         // above to sort by game score.
         RecordEnumeration re = recordStore.enumerateRecords(null, this,
            true);
         printScoresHelper(re);
     }
     catch (RecordStoreException rse) {
         System.out.println(rse);
         rse.printStackTrace();
     }
        }

        /**
         * This method prints all of the scores for a given player,
         * sorted by game score.
         */
        public void printScores(String playerName)
        {
     try {
         // Enumerate the records using the comparator and filter
         // implemented above to sort by game score.
         RecordEnumeration re = recordStore.enumerateRecords(this, this,
            true);
         printScoresHelper(re);
     }
     catch (RecordStoreException rse) {
         System.out.println(rse);
         rse.printStackTrace();
     }
        }

        public static void main(String[] args)
        {
     RMSGameScores rmsgs = new RMSGameScores();
     rmsgs.addScore(100, "Alice");
     rmsgs.addScore(120, "Bill");
     rmsgs.addScore(80, "Candice");
     rmsgs.addScore(40, "Dean");
     rmsgs.addScore(200, "Ethel");
     rmsgs.addScore(110, "Farnsworth");
     rmsgs.addScore(220, "Farnsworth");
     System.out.println("All scores");
     rmsgs.printScores();
     System.out.println("Farnsworth's scores");
     RMSGameScores.playerNameFilter = "Farnsworth";
     rmsgs.printScores("Farnsworth");
        }
    }

    Read and write to the record store:

    
    

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

    public class ReadWrite extends MIDlet
    {
    private RecordStore rs = null;
    static final String REC_STORE = "db_1";

    public ReadWrite()
    {
    openRecStore(); // Create the record store

    // Write a few records and read them back
    writeRecord("J2ME and MIDP");
    writeRecord("Wireless Technology");
    readRecords();

    closeRecStore(); // Close record store
    deleteRecStore(); // Remove the record store
    }

    public void destroyApp( boolean unconditional )
    {
    }

    public void startApp()
    {
    // There is no user interface, go ahead and shutdown
    destroyApp(false);
    notifyDestroyed();
    }

    public void pauseApp()
    {
    }

    public void openRecStore()
    {
    try
    {
    // The second parameter indicates that the record store
    // should be created if it does not exist
    rs = RecordStore.openRecordStore(REC_STORE, true );
    }
    catch (Exception e)
    {
    db(e.toString());
    }
    }

    public void closeRecStore()
    {
    try
    {
    rs.closeRecordStore();
    }
    catch (Exception e)
    {
    db(e.toString());
    }
    }

    public void deleteRecStore()
    {
    if (RecordStore.listRecordStores() != null)
    {
    try
    {
    RecordStore.deleteRecordStore(REC_STORE);
    }
    catch (Exception e)
    {
    db(e.toString());
    }
    }
    }

    public void writeRecord(String str)
    {
    byte[] rec = str.getBytes();

    try
    {
    rs.addRecord(rec, 0, rec.length);
    }
    catch (Exception e)
    {
    db(e.toString());
    }
    }

    public void readRecords()
    {
    try
    {
    // Intentionally make this too small to test code below
    byte[] recData = new byte[5];
    int len;

    for (int i = 1; i <= rs="" getnumrecords="" i="" if="" getrecordsize=""> recData.length)
    recData = new byte[rs.getRecordSize(i)];
    len = rs.getRecord(i, recData, 0);
    System.out.println("Record #" + i + ": " + new String(recData, 0, len));
    System.out.println("------------------------------");
    }
    }
    catch (Exception e)
    {
    db(e.toString());
    }
    }
    private void db(String str)
    {
    System.err.println("Msg: " + str);
    }
    }



© 2015 by Learncertification All Rights Reserved. The certification names are the trademarks of their respective owners. Terms & Privacy Policy