📄 addrecorddemo_2.java
字号:
package PhoneBook;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.*;
/**
* 添加记录,并且把记录遍历出来
*/
public class AddRecordDemo_2 extends MIDlet implements CommandListener {
//定义按钮
private final static Command exitCommand = new Command("退出", Command.EXIT,1);
private final static Command yesCommand = new Command("确定", Command.SCREEN,1);
private final static Command backCommand = new Command("返回", Command.BACK,1);
private Display display;
private List mainList;//列表
private TextBox tb;//文本框
private RecordStore rs;
public AddRecordDemo_2() {
display = Display.getDisplay(this);
tb = new TextBox("数据库例子", "List", 1000, 0);
tb.addCommand(backCommand);
tb.setCommandListener(this);
}
protected void startApp() {
String[] stringArray = { "添加记录", "读取记录" };
mainList = new List("数据库例子", Choice.IMPLICIT, stringArray, null);
mainList.addCommand(exitCommand);
mainList.setCommandListener(this);
display.setCurrent(mainList);
try {
rs = RecordStore.openRecordStore("Record1", true);
} catch (Exception e) {
rs = null;
}
}
protected void destroyApp(boolean unconditional) {
}
protected void pauseApp() {
}
public void commandAction(Command c, Displayable d) {
if (d.equals(mainList)) {
if (c == List.SELECT_COMMAND) {
if (d.equals(mainList)) {
switch (((List) d).getSelectedIndex()) {
case 0:
//清空屏幕
tb.setString("");
tb.addCommand(yesCommand);
display.setCurrent(tb);
break;
//如果选择了读取数据类表
case 1:
String str = "";
try {
if (rs.getNumRecords() > 0) {
RecordEnumeration re = rs.enumerateRecords( null, null, false);
while (re.hasNextElement()) {
//把2进制数据转换为字符串
String temp = new String(re.nextRecord());
str = temp + "\r\n" + str;
}
}
} catch (Exception e) {
System.out.println(e);
}
tb.setString(str);
//隐藏确定按钮
tb.removeCommand(yesCommand);
display.setCurrent(tb);
break;
}
}
}
} else {
//如果是【确定】按钮,则添加新记录
if (c == yesCommand) {
if (rs != null) {
byte[] data = tb.getString().getBytes();
int i = 0;
try {
i = rs.addRecord(data, 0, data.length);
} catch (RecordStoreException e) {
System.out.println(e);
e.printStackTrace();
}
}
display.setCurrent(mainList);
}
if (c == backCommand) {
display.setCurrent(mainList);
}
}
if (c == exitCommand) {
try {
rs.closeRecordStore();
rs = null;
} catch (Exception e) {
}
destroyApp(false);
notifyDestroyed();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -