【发布时间】:2014-06-22 19:10:33
【问题描述】:
在我正在开发的应用程序中,我需要存储客户、产品及其价格的数据。 为了持久化我使用 RMS 的数据,但知道 RMS 不支持直接对象序列化,并且由于我读取的数据已经采用 json 格式,我将每个 JSONObject 存储为其字符串版本,如下所示:
rs = RecordStore.openRecordStore(mRecordStoreName, true);
JSONArray jsArray = new JSONArray(data);
for (int i = 0; i < jsArray.length(); i++) {
JSONObject jsObj = jsArray.getJSONObject(i);
stringJSON = jsObj.toString();
addRecord(stringJSON, rs);
}
addRecord方法
public int addRecord(String stringJSON, RecordStore rs) throws JSONException,RecordStoreException {
int id = -1;
byte[] raw = stringJSON.getBytes();
id= rs.addRecord(raw, 0, raw.length);
return id;
}
所以我有三个 RecordStores(客户、产品和它们的价格),我对它们中的每一个都进行了如上所示的保存以保存它们的相应数据。
我知道这可能是一个可行的解决方案,但我确信一定有更好的实现。更重要的是,考虑到这三个“表”,我将执行搜索、排序等。
在这些情况下,在继续搜索或排序之前必须反序列化似乎不是一个好主意。
这就是我想问你们的原因。根据您的经验,如何将自定义对象存储在 RMS 中以便以后使用?
非常感谢您的所有 cmets 和建议。
编辑
当您为每个字段定义一个固定的最大长度时,似乎更容易处理记录。所以这就是我尝试过的:
1) 首先,这是我用来从记录存储中检索值的类:
public class Customer {
public int idCust;
public String name;
public String IDNumber;
public String address;
}
2) 这是我用来将每个 jsonObject 保存到记录存储的代码:
RecordStore rs = null;
try {
rs = RecordStore.openRecordStore(mRecordStoreName, true);
JSONArray js = new JSONArray(data);
for (int i = 0; i < js.length(); i++) {
JSONObject jsObj = js.getJSONObject(i);
byte[] record = packRecord(jsObj);
rs.addRecord(record, 0, record.length);
}
} finally {
if (rs != null) {
rs.closeRecordStore();
}
}
packRecord 方法:
private byte[] packRecord(JSONObject jsonObj) throws IOException, JSONException {
ByteArrayOutputStream raw = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(raw);
out.writeInt(jsonObj.getInt("idCust"));
out.writeUTF(jsonObj.getString("name"));
out.writeUTF(jsonObj.getString("IDNumber"));
out.writeUTF(jsonObj.getString("address"));
return raw.toByteArray();
}
3) 这就是我从记录存储中提取所有记录的方式:
RecordStore rs = null;
RecordEnumeration re = null;
try {
rs = RecordStore.openRecordStore(mRecordStoreName, true);
re = rs.enumerateRecords(null, null, false);
while (re.hasNextElement()) {
Customer c;
int idRecord = re.nextRecordId();
byte[] record = rs.getRecord(idRecord);
c = parseRecord(record);
//Do something with the parsed object (Customer)
}
} finally {
if (re != null) {
re.destroy();
}
if (rs != null) {
rs.closeRecordStore();
}
}
parseRecord方法:
private Customer parseRecord(byte[] record) throws IOException {
Customer cust = new Customer();
ByteArrayInputStream raw = new ByteArrayInputStream(record);
DataInputStream in = new DataInputStream(raw);
cust.idCust = in.readInt();
cust.name = in.readUTF();
cust.IDNumber = in.readUTF();
cust.address = in.readUTF();
return cust;
}
这就是我实施史密斯先生建议的方式(希望这是他的想法)。但是,我仍然不太确定如何实现搜索。
我差点忘了提到,在我对代码进行这些更改之前,我的 RecordStore 的大小是 229048 字节,现在只有 158872 字节 :)
【问题讨论】: