2010-03-22 45 views
0

我目前正在做一些J2ME開發。我遇到了一個問題,用戶可以向記錄存儲區中添加和刪除元素,並且如果記錄被刪除,那麼該記錄留空,而其他記錄不會向上移動。我試圖想出一個循環來檢查一個記錄是否有任何內容(如果它已被刪除),如果它確實那麼我想將該記錄的內容添加到列表中。 我的代碼是類似如下:在Java中使用RecordStore J2ME

 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); 
     } 

     } 

當它到達rs.getRecordSize(我),我總是得到一個「javax.microedition.rms.InvalidRecordIDException:錯誤找到記錄」。我知道這是由於記錄空了,但我想不出解決這個問題的辦法。

任何幫助將不勝感激。

在此先感謝。

+3

7個問題,0個接受的答案和0票。這看起來不太好。 – 2010-03-22 15:58:40

回答

6

您應該使用RecordEnumeration訪問記錄:

RecordEnumeration renum = rs.enumerateRecords(null, null, false); 
while (renum.hasNextElement()) 
{ 
    int index = renum.nextRecordId(); 
    if (store.getRecordSize(index) == STORE_LEN) 
    { 

    } 
} 

你不能依靠的recordId的任何有用。使用不同的技術來重新分配已刪除的記錄。

+0

什麼是STORE_LEN? – me123 2010-03-23 14:47:46

+0

這是記錄的長度。你的應用程序應該知道它。我用它來區分不同的記錄。當然,你不必這樣做。這個想法是你使用枚舉,使用nextRecordId獲取索引,然後使用getRecordSize獲取大小。 – kgiannakakis 2010-03-23 14:52:48

0

您可以嘗試使用以下方法:

/** 
* 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; 
    } 

} 
1

爲了讓您的記錄真正刪除,你必須關閉德RecordStore中。操作RecordStore的正確方法是打開它,並使用它最終關閉它。希望這對你有用