Java Reference
In-Depth Information
public int getRecord(int recordId, byte[] buffer, int offset)
throws RecordStoreNotOpenException,
InvalidRecordIDException,
RecordStoreException
This method returns the number of bytes that were copied into your array. If the array you
supply is not large enough to hold the record, an
ArrayOutOfBoundsException
will be thrown.
You can find out the size of a particular record ahead of time by calling
getRecordSize()
.
Given a
RecordStore rs
and a record ID
id
, here is one way to retrieve a record's data:
byte[] retrieved = new byte[rs.getRecordSize(id)];
rs.getRecord(id, retrieved, 0);
String retrievedString = new String(retrieved);
If you're going to be pulling many records out of the record store, you probably won't want
to create a new byte array each time. For efficiency, you would create one array and use it over
and over again to pull records out of the record store. One way to create the buffer is to make it
as large as the largest record in the record store. If that's not practical, or if you don't know how
large the largest record will be, you can simply check the size of each record before you retrieve
it. If you come across a record that's larger than the buffer, you could create a larger buffer.
If you're not worried about memory usage or speed, then you might as well use the other
form of
getRecord()
, which is essentially the same as the previous code example:
byte[] retrieved = rs.getRecord(id);
Deleting and Replacing Records
So far you've seen how to add new records and retrieve them. There are two more record
operations supported by
RecordStore
. First, you can remove a record by passing its ID to
deleteRecord()
. Second, you can replace the data of an existing record by calling the following
method:
public void setRecord(int recordId, byte[] newData, int offset, int numBytes)
throws RecordStoreNotOpenException,
InvalidRecordIDException,
RecordStoreException,
RecordStoreFullException
Getting RecordStore Record Information
The
RecordStore
keeps an internal counter that it uses to assign record IDs. You can find out
what the next record ID will be by calling
getNextRecordID()
. And you can find out how many
records exist in the
RecordStore
by calling
getNumRecords()
.
Saving User Preferences
Let's put some of this knowledge to work. This section details a simple MIDlet that saves a user
name and password in a
RecordStore
. Each time the MIDlet is used, it can load the user name
Search WWH ::
Custom Search