AddressBookMIDLet类(见下)包含一个 AddressDB对象,一个 List GUI组件和一个 Back命令和 Exit命令。我们将使用 AddressDB类中的 addAddress()方法,把地址添加到数据库中。在 startApp()方法中,使用调用 List.append()和 AddressDB.addAddress()方法来填充 List。这是在 commandAction()内部完成的,其结果就是创建一个新的文本框并且添加显示出来。因为 cmdBack命令对象是使用 Command.BACK变量创建的,当又一个元素被添加显示时,环境知道显示一个 Back命令按钮。然后通过把显示焦点设置回 mnuMain列表对象,处理 “back”命令事件。
import javax.microedition.midlet.*;import javax.microedition.lcdui.*;
public class AddressBookMIDLet extends MIDlet implementsCommandListener {
Display display = null;
List mnuMain = null;
TextBox txtAddress = null;
static final Command cmdBack = new Command("Back", Command.BACK,0);
static final Command cmdExit = new Command("Exit", Command.STOP,3);
AddressDB dbAddress = null;
public AddressBookMIDLet()
{
dbAddress = new AddressDB();
file://杜撰的地址
dbAddress.addAddress("Bill Gates", "123 Elm Street");
dbAddress.addAddress("George Bush", "742 Avenue B");
dbAddress.addAddress("Yuki Aka", "853 Franklin Avenue");
dbAddress.addAddress("Oba Muchow", "101 Scenic Highway");
dbAddress.addAddress("Bill Clinton", "741 Highway 101");
}
public void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
mnuMain = new List("Addresses", Choice.IMPLICIT);
int count = dbAddress.recordCount();
for (int i=0; i < count; i++) {
mnuMain.append(dbAddress.getName(i+1), null);
}
mnuMain.addCommand(cmdExit);
mnuMain.setCommandListener(this);
display.setCurrent(mnuMain);
}
public void pauseApp() {
display = null;
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
public void commandAction(Command c, Displayable d) {
String str = c.getLabel();
if (str.equals("Exit")) {
destroyApp(true);
}
else if (str.equals("Back")) {
display.setCurrent(mnuMain);
}
else {
List select = (List)display.getCurrent();
String txtSelect =
AddressDB.getName(select.getSelectedIndex() + 1) + ", " +
dbAddress.getAddress(select.getSelectedIndex() + 1);
txtAddress = new TextBox("Address", txtSelect, 255,
TextField.ANY);
txtAddress.addCommand(cmdBack);
txtAddress.setCommandListener(this);
display.setCurrent(txtAddress);
}
}
} |
四、本节小结
在本例子中,我示范如何使用 J2ME记录管理系统(RMS)构造一个基本的通讯录应用程序,支持局部数据存储的能力是 J2ME与其他无线技术比如 WML/WMLScript的不同之处,当然,要使来自移动设备的数据与一个企业数据库同步需要附加的网络和输入/输出性能,下面我想谈谈J2ME网络功能。
|