📄 formidlet.java
字号:
package com.j2medev.chapter4;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
public class ForMIDlet extends MIDlet implements CommandListener{
private Display display = null;
private List list = null;
private RecordStore rs = null;
public static final Command exitCommand = new Command("退出",Command.EXIT,1);
public static final Command deleteCommand = new Command("删除",Command.OK,2);
public void startApp() {
initMIDlet();
}
private void initMIDlet(){
if(display == null)
display = Display.getDisplay(this);
openDatabase();
//从RecordStore读取记录数据
String[] record = getRecord();
if(record != null){
list = new List("记录集合",List.IMPLICIT, record,null);
list.setSelectCommand(deleteCommand);
list.addCommand(exitCommand);
list.setCommandListener(this);
display.setCurrent(list);
}else{
displayError();
}
}
//如果不能正确读取RecordStore中的数据则显示错误信息
private void displayError(){
Form form = new Form("结果");
form.append("读取数据记录出错");
display.setCurrent(form);
}
//使用for循环的方式读取RecordStore中的记录,注意这种方式不应该被采用。
private String[] getRecord(){
String[] record = null;
try{
int length = rs.getNumRecords();
record = new String[length];
for(int i = 1;i<=length;i++){
byte[] data = rs.getRecord(i);
//recordId的初始值为1,数组索引从0开始。
record[i-1] = new String(data);
}
}catch(RecordStoreException e){
record = null;
e.printStackTrace();
}
return record;
}
//初始化RecordStore数据
private void openDatabase(){
try{
rs = RecordStore.openRecordStore("forloop1",true);
if(rs.getNumRecords() <= 0){
for(int i = 1;i<6;i++){
String s = "记录"+i;
byte[] data = s.getBytes();
rs.addRecord(data, 0,data.length);
}
}
}catch(RecordStoreException e){
e.printStackTrace();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command cmd,Displayable displayable){
if(cmd == exitCommand){
destroyApp(false);
notifyDestroyed();
}else if(cmd == deleteCommand){
//删除记录并重新设置List
int index = list.getSelectedIndex();
try{
rs.deleteRecord(index+1);
}catch(RecordStoreException e){
e.printStackTrace();
}
String[] record = getRecord();
if(record == null){
displayError();
}else{
list.deleteAll();
for(int i = 0;i<record.length;i++){
list.append(record[i],null);
}
display.setCurrent(list);
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -