Using RMS to Store Persistent Data
There are times when you will want your MIDlet to be able to store data that is persistent across multiple executions of the application. In the context of video games, for example, you may want to save the high scores, or retain the game state so that the player can continue later. In this tutorial, we will look at how to use a component of MIDP called Record Management System, or RMS, as a means of storing persistent application data.
The classes and interfaces related to Record Management System can be found in the javax.microedition.rms package. Persisted data is stored in a RecordStore object. As the name implies, RecordStore objects store a collection of records. In database terminology, a RecordStore object is synonymous with a table. Each record is identified by a unique integer value, or recordId. ID values are created sequentially, with the first record having an ID of 1. An application can have multiple RecordStore objects. RecordStore objects have MIDlet Suite scope; that is, they can only be accessed by MIDlets in the same JAR file.
Let’s look at an example. The following code demonstrates how to save a single integer value, in this case, a high score. For simplicity, the RecordStore in this example will only ever contain one record, the one for the high score. We will convert the integer to a String, which then can be easily converted into a byte array for the record.
import javax.microedition.rms.*;
/**
* Saves the high score.
*/
public void setHighScore(int highScore) {
try {
// Open or create RecordStore
RecordStore recordStore
= RecordStore.openRecordStore("highScore", true);
// Convert to String and then byte array
String highScoreString = ""+highScore;
byte bytes[] = highScoreString.getBytes();
// Add or create record
if(recordStore.getNumRecords() == 0) {
// Record does not exist; create it
recordStore.addRecord(bytes, 0, bytes.length);
} else {
// Update existing (first) record
recordStore.setRecord(1, bytes, 0, bytes.length);
}
} catch(RecordStoreException e) {
System.err.println("Could not save high score");
}
}
The code below demonstrates how to read the high score. If there is no saved high score, the method returns zero.
/**
* Looks for a saved high score.
*/
public int getHighScore() {
try {
// Open RecordStore
RecordStore recordStore
= RecordStore.openRecordStore("highScore", false);
// Get first record, where highScore is stored
byte[] bytes = recordStore.getRecord(1);
// Convert to string, and then to int
String highScoreString = new String(bytes);
int highScore = Integer.parseInt(highScoreString);
return highScore;
} catch(RecordStoreException e) {
// No RecordStore found
System.out.println("RecordStore Not Found");
return 0;
}
}
Bookmark this article: del.icio.us Digg Furl Reddit blogmarks Google Spurl StumbleUpon Technorati Yahoo!