【发布时间】:2009-11-09 22:51:47
【问题描述】:
我正在使用 J2ME 构建一个移动应用程序,我发现我写入 RecordStore 的数据可以在程序仍在运行时访问,但在退出并重新启动后会丢失。没有抛出异常,数据只是丢失了。
更新:感谢大家的建议。我在 Windows 7 上使用 NetBeans。我不确定它是使用我之前安装的 WTK 版本还是它在其他地方安装的另一个版本。我检查了我的 WTK 文件夹中是否有 Pavel 所写的文件,但找不到它们。现在我正在我的手机上测试需要持久性的功能以及模拟器中的所有其他内容,但是能够测试模拟器中的所有内容当然会好得多。
private RecordStore recordStore = null;
public MyMIDlet() {
readStuff(); // output: nothing found in recordStore :(
saveStuff();
readStuff(); // output: stuff
}
private void readStuff() {
try {
recordStore = RecordStore.openRecordStore(REC_STORE, true);
int n = recordStore.getNumRecords();
String stuff;
if (n == 0) {
stuff = "nothing found in recordStore :(";
}
else {
stuff = new String(recordStore.getRecord(1));
}
System.out.println(stuff);
}
catch (Exception e) {
System.out.println("Exception occured in readStuff: " + e.getMessage());
}
finally {
if (recordStore != null) {
try {
recordStore.closeRecordStore();
}
catch (Exception e) {
// ignore
}
}
}
}
private void saveStuff() {
try {
recordStore = RecordStore.openRecordStore(REC_STORE, true);
int n = recordStore.getNumRecords();
byte[] stuff = "stuff".getBytes();
recordStore.addRecord(stuff, 0, stuff.length);
} catch (Exception e) {
System.out.println("Exception occured in saveStuff: " + e.getMessage());
} finally {
if (recordStore != null) {
try {
recordStore.closeRecordStore();
} catch (Exception e) {
// ignore
}
}
}
}
【问题讨论】:
-
这是在实体手机还是模拟器上运行?数据是否在模拟器会话之间持久存在取决于您退出的方式以及您的设置。模拟器重启可能会删除持久化的数据。
-
它在模拟器中运行,但现在我也将在手机上尝试它。谢谢。
-
它确实在我的手机上工作。非常感谢! :)
-
你现在可以用这个答案来回答你自己的问题了!