Using RecordStore in Java J2ME
I am currently doing some J2ME development. I am having a pro开发者_运维百科blem in that a user can add and remove elements to the record store, and if a record gets deleted, then that record is left empty and the others don't move up one. I'm trying to come up with a loop that will check if a record has anything in it (incase it has been deleted) and if it does then I want to add the contents of that record to a list. My code is similar to as follows:
for (int i = 1; i <= rs.getNumRecords(); i++)
{
// Re-allocate if necessary
if (rs.getRecordSize(i) > recData.length)
recData = new byte[rs.getRecordSize(i)];
len = rs.getRecord(i, recData, 0);
st = new String(recData, 0, len);
System.out.println("Record #" + i + ": " + new String(recData, 0, len));
System.out.println("------------------------------");
if(st != null)
{
list.insert(i-1, st, null);
}
}
When it gets to rs.getRecordSize(i), I always get a "javax.microedition.rms.InvalidRecordIDException: error finding record". I know this is due to the record being empty but I can't think of a way to get around this problem.
Any help would be much appreciated.
Thanks in advance.
You should use a RecordEnumeration to visit the records:
RecordEnumeration renum = rs.enumerateRecords(null, null, false);
while (renum.hasNextElement())
{
int index = renum.nextRecordId();
if (store.getRecordSize(index) == STORE_LEN)
{
}
}
You can't rely on the recordId for anything useful. Use a different technique to reallocate a deleted record.
In order to have your records truly deleted you have to close de RecordStore. The correct way to operate a RecordStore is by opening it, using it an finally closing it. Hope this is usefull to you
You could try to use the following method:
/**
* checks if record i is a valid records
* @param i (recordId
* @return true/false
*/
public boolean isValidRecord(int id) {
try {
recordStore.getRecordSize(id);
return true;
} catch (RecordStoreNotOpenException e1) {
e1.printStackTrace();
return false;
} catch (InvalidRecordIDException e1) {
//e1.printStackTrace(); //this printStackTrace is hidden on purpose: the error is in fact used to find out if the record id is valid or not.
return false;
} catch (RecordStoreException e1) {
e1.printStackTrace();
return false;
}
}
精彩评论