Java Reference
In-Depth Information
// Now save the preferences records.
Enumeration keys = mHashtable.keys();
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
String value = get(key);
String pref = key + "|" + value;
byte[] raw = pref.getBytes();
rs.addRecord(raw, 0, raw.length);
}
}
finally {
if (re != null) re.destroy();
if (rs != null) rs.closeRecordStore();
}
}
}
RecordMIDlet
saves the updated values back to the
RecordStore
in its
destroyApp()
method. It
saves the user name and password from the user interface in the
Preferences
object, then calls
the
save()
method to write the new values out to the
RecordStore
. The
save()
method removes
all records from the record store, and then adds each key and value pair.
To test out the MIDlet, enter some text into the user name and password fields. Then exit
the MIDlet and restart it. You will see the same values loaded into the text fields.
Note that
Preferences
only deals with
String
values, but records can contain any data
packed into a byte array. By using stream classes from the
java.io
package, it's possible to
store complex data types in records. For example, you could use a
DataOutputStream
wrapped
around a
ByteArrayOutputStream
to generate data to be written into the record store. To extract
data values, you would use a
DataInputStream
wrapped around a
ByteArrayInputStream
based
on the record data.
Listening for Record Changes
RecordStore
s support a JavaBeans-style listener mechanism. Interested objects can listen for
changes to a record store by registering themselves as listeners.
The listener interface is
javax.microedition.rms.RecordListener
. You can manage a
RecordStore
's listeners with the following two methods:
public void addRecordListener(RecordListener listener)
public void removeRecordListener(RecordListener listener)
The
RecordListener
interface has three methods:
recordAdded()
,
recordChanged()
, and
recordDeleted()
. These are called whenever a record is added, changed, or deleted. Each method
is passed the
RecordStore
involved and the ID of the record in question.
Search WWH ::
Custom Search