J2ME通讯簿实例

J2ME通讯簿实例
作者:万立中             时间:2010-06-12                       转载:请注明www.wanlizhong.com

package phonebook;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.RecordStore;

public class PhoneBookMIDlet extends MIDlet implements CommandListener {
private final static Command exitCommand =
new Command(BookConstant.CmdExitLabel,Command.EXIT, 1);
private final static Command confirmCommand =
new Command(BookConstant.CmdOkLabel,Command.SCREEN, 1);
private Display display;
private List mainList;
private RecordStore rs;
public PhoneBookMIDlet() {
display = Display.getDisplay(this);
}
protected void startApp() {
// 创建图像对象
Image[] imageArray = null;
try {
// 读取图像资源
Image icon = Image.createImage(“/res/doc.png”);
// 创建图像数组
imageArray = new Image[] {
icon, icon, icon, icon};
}
catch (java.io.IOException err) {
imageArray = null;
}
mainList = new List(BookConstant.Title,
Choice.IMPLICIT,
BookConstant.menu,
imageArray);
mainList.addCommand(exitCommand);
mainList.addCommand(confirmCommand);
mainList.setCommandListener(this);
display.setCurrent(mainList);
//打开记录文件,如果不存在则创建
try {
rs = RecordStore.openRecordStore(“MyPhoneBook”, 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 || c == confirmCommand) {
if (d.equals(mainList)) {
switch ( ( (List) d).getSelectedIndex()) {
case 0:
//添加新纪录
NewRecordForm newRF =
new NewRecordForm(BookConstant.record_added,
mainList, this, rs);
display.setCurrent(newRF);
break;
case 1:
//显示电话本
ListRecord list =
new ListRecord(BookConstant.listPhoneTitle,
Choice.IMPLICIT,
mainList, this,rs);
display.setCurrent(list);
break;
case 2:
FindRecord fr = new FindRecord(mainList, this, rs);
display.setCurrent(fr);
break;
case 3:
//删除记录
DeleteRecord dr = new DeleteRecord(mainList, this, rs);
display.setCurrent(dr);
break;
}
}
}
}
//如果键入退出按钮,则退出程序
if (c == exitCommand) {
//关闭记录文件
try {
rs.closeRecordStore();
rs = null;
}
catch (Exception e) {
}
destroyApp(false);
notifyDestroyed();
}
}
}

package phonebook;
public class BookConstant {
public static final String alertTitle = “信息提示”;
public static final String listTitle = “主菜单”;
public static final String Title = “电话簿”;
public static final String DelTitle = “删除记录”;
public static final String EditInfoTitle = “查看和修改记录”;
public static final String FindTitle = “查询记录”;
public static final String inputNameLabel = “输入名字”;
public static final String CmdOkLabel=”确定”;
public static final String CmdExitLabel=”退出”;
public static final String CmdBackLabel=”返回”;
public static final String CmdSaveLabel=”保存”;
public static final String CmdDetailLabel=”查看”;
public static final String CmdFindLabel=”查找”;
public static final String CmdDelLabel=”删除”;
public static final String[] menu = {  “添加新记录”,”浏览电话簿”,”查找记录”,”删除记录”};
public static final String author = “作者”;
public static final String add_record = “添加记录”;
public static final String delete_phonebook = “删除电话本?”;
public static final String name = “姓名”;
public static final String mobile = “移动电话”;
public static final String phone = “固定电话”;
public static final String email = “电子信箱”;
public static final String choice = ” 选项”;
public static final String detail = “详细信息”;
public static final String listPhoneTitle = “电话本列表”;
public static final String search = “查询电话”;
public static final String userNameNull = “用户名不能为空”;
public static final String mobilePhoneNull = “电话号码不能为空”;
public static final String deleteing = “正在删除纪录…”;
public static final String gettingList = “正在浏览纪录…”;
public static final String record_added = “添加记录完成”;
public static final String record_exist = “记录已经存在”;
public static final String DELETE_RECORD = “删除”;
public static final String DETAIL_INFO = “详细信息”;
public static final String nameExistInfo = “你输入的姓名已经存在,请输入其他名字”;
public static final String rsName = “phonebook”;
public static final String rs_index = “index”;
}

package phonebook;

import java.io.*;
public class BookAccount {
private String userName = “”;
private String mobilePhone = “”;
private String email = “”;
private String phone = “”;
public BookAccount(String userName,
String mobilePhone,
String email,
String phone) {
this.userName = userName;
this.mobilePhone = mobilePhone;
this.email = email;
this.phone = phone;
}
public BookAccount() {
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public byte[] serialize() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeUTF(userName);
dos.writeUTF(mobilePhone);
dos.writeUTF(email);
dos.writeUTF(phone);
baos.close();
dos.close();
return baos.toByteArray();
}
public static BookAccount deserialize(byte[] data) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
DataInputStream dis = new DataInputStream(bais);
BookAccount account = new BookAccount();
account.userName = dis.readUTF();
account.mobilePhone = dis.readUTF();
account.email = dis.readUTF();
account.phone = dis.readUTF();
bais.close();
dis.close();
return account;
}
public static boolean matches(byte[] data, String userName)
throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
DataInputStream dis = new DataInputStream(bais);
try {
return (dis.readUTF()).equals(userName);
}
catch (IOException e) {
e.printStackTrace();
return false;
}
}
}

package phonebook;
import javax.microedition.rms.*;
public class FindFilter implements RecordFilter {
private String filterName = null;
public FindFilter(String name) {
this.filterName = name;
}
public boolean matches(byte[] rec) {
BookAccount account = null;
String name = null;
try {
account = BookAccount.deserialize(rec);
name = account.getUserName();
account = null;
}
catch (Exception e) {
account = null;
System.out.println(“error”);
}
//按name搜索
if (name != null) {
if (filterName.equals(name)) {
return true;
}
}
return false;
}
}

package phonebook;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordFilter;
import javax.microedition.rms.RecordStore;
public class FindRecord extends Form implements CommandListener {
private Displayable dis;
private MIDlet mid;
private RecordStore rs = null;
private RecordEnumeration re = null;
private static final Command findCommand =
new Command(BookConstant.CmdFindLabel, Command.OK, 1);
private static final Command backCommand =
new Command(BookConstant.CmdBackLabel, Command.BACK,2);
private TextField tf;
public FindRecord(Displayable dis, MIDlet mid, RecordStore rs) {
super(BookConstant.FindTitle);
tf = new TextField(BookConstant.inputNameLabel, null, 120, TextField.ANY);
//设置控件的布局
tf.setLayout(Item.LAYOUT_NEWLINE_AFTER);
this.append(tf);
this.dis = dis;
this.mid = mid;
this.rs = rs;
this.addCommand(backCommand);
this.addCommand(findCommand);
this.setCommandListener(this);
}
public void commandAction(Command c, Displayable d) {
if (c == backCommand) {
Display.getDisplay(mid).setCurrent(dis);
}
if (c == findCommand) {
RecordFilter rf = new FindFilter(tf.getString());
RecordEnumeration re = null;
try {
re = rs.enumerateRecords(rf, null, false);
}
catch (Exception e) {
}
//查找成功
if (re.numRecords() > 0) {
BookAccount account = null;
int recordID;
try {
byte[] rec;
recordID = re.nextRecordId();
rec = rs.getRecord(recordID);
account = BookAccount.deserialize(rec);
StringItem name = new StringItem(BookConstant.name+”:”, account.getUserName());
StringItem mobilePhone = new StringItem(BookConstant.mobile+”:”,
account.getMobilePhone());
StringItem phone = new StringItem(BookConstant.phone+”:”, account.getPhone());
StringItem email = new StringItem(BookConstant.email+”:”, account.getEmail());
name.setLayout(Item.LAYOUT_NEWLINE_AFTER);
mobilePhone.setLayout(Item.LAYOUT_NEWLINE_AFTER);
phone.setLayout(Item.LAYOUT_NEWLINE_AFTER);
email.setLayout(Item.LAYOUT_NEWLINE_AFTER);
this.append(name);
this.append(mobilePhone);
this.append(phone);
this.append(email);
account = null;
re.destroy();
}
catch (Exception e) {
account = null;
System.out.println(“error”);
}
}
}
}
}

package phonebook;
import javax.microedition.rms.*;
public class SortComparator implements RecordComparator {
private String name_1, name_2;
public int compare(byte[] rec1, byte[] rec2) {
BookAccount account = null;
try {
account = BookAccount.deserialize(rec1);
name_1 = account.getUserName();
account = BookAccount.deserialize(rec2);
name_2 = account.getUserName();
account = null;
}
catch (Exception e) {
account = null;
System.out.println(“error”);
}
//按照名字顺序排序
if (name_1.compareTo(name_2) == 0) {
return RecordComparator.EQUIVALENT;
}
else if (name_1.compareTo(name_2) < 0) {
return RecordComparator.PRECEDES;
}
return RecordComparator.FOLLOWS;
}
}

package phonebook;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.*;
public class ListRecord extends List implements CommandListener {
private Displayable dis;
private MIDlet mid;
private RecordStore rs = null;
private RecordEnumeration re = null;
private static final Command lookCommand =
new Command(BookConstant.CmdDetailLabel, Command.OK, 1);
private static final Command backCommand =
new Command(BookConstant.CmdBackLabel, Command.BACK,2);
public ListRecord(String title,
int listType,
Displayable dis,
MIDlet mid,
RecordStore rs) {
super(title, listType);
this.dis = dis;
this.mid = mid;
this.rs = rs;
this.addCommand(backCommand);
this.addCommand(lookCommand);
this.setCommandListener(this);
SortComparator sortCom = new SortComparator();
if (rs != null) {
try {
Image icon = Image.createImage(“/txt.png”);
//按照名字的字符串大小排序
re = rs.enumerateRecords(null, sortCom, true);
//添加列表项
while (re.hasNextElement()) {
//分解数据库记录数据
BookAccount account = BookAccount.deserialize(re
.nextRecord());
//把名字添加到列表中
int index = this.append(account.getUserName(), icon);
}
}
catch (Exception e) {
}
finally {
if (re != null)
re.destroy();
}
}
}
public void commandAction(Command c, Displayable d) {
if (c == backCommand) {
Display.getDisplay(mid).setCurrent(dis);
}
if (c == lookCommand) {
//进入记录编辑界面
EditDetailInfo edInfo =
new EditDetailInfo(BookConstant.EditInfoTitle,
this, mid,rs,
this.getString(this.getSelectedIndex()));
Display.getDisplay(mid).setCurrent(edInfo);
}
}
}

package phonebook;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;
public class NewRecordForm extends Form implements CommandListener {
private TextField nameField;
private TextField mobileField;
private TextField phoneField;
private TextField emailField;
private Displayable dis;
private MIDlet mid;
private RecordStore rs = null;
private static final Command saveCommand =
new Command(BookConstant.CmdSaveLabel, Command.OK, 2);
private static final Command backCommand =
new Command(BookConstant.CmdBackLabel, Command.BACK, 3);
public NewRecordForm(String title,
Displayable dis,
MIDlet mid,
RecordStore rs) {
super(title);
this.dis = dis;
this.mid = mid;
this.rs = rs;
nameField = new TextField(BookConstant.name, null, 25, TextField.ANY);
mobileField = new TextField(BookConstant.mobile, null, 25,
TextField.PHONENUMBER);
phoneField = new TextField(BookConstant.phone, null, 25,
TextField.PHONENUMBER);
emailField = new TextField(BookConstant.email, null, 25,
TextField.EMAILADDR);
this.append(nameField);
this.append(mobileField);
this.append(phoneField);
this.append(emailField);
this.addCommand(saveCommand);
this.addCommand(backCommand);
this.setCommandListener(this);
}
public void commandAction(Command c, Displayable d) {
if (c == saveCommand) {
if (rs != null) {
if (nameField.getString().length() == 0) {
Alert a_name = new Alert(BookConstant.alertTitle,
BookConstant.userNameNull,
null, AlertType.ERROR);
a_name.setTimeout(Alert.FOREVER);
Display.getDisplay(mid).setCurrent(a_name);
return;
}
//查找是否已经存在相同的名字
RecordFilter rf = new FindFilter(nameField.getString());
RecordEnumeration re = null;
try {
re = rs.enumerateRecords(rf, null, false);
// if (re.hasNextElement()) {
//   re.nextRecord();
// }
}
catch (Exception e) {
}
//如果已经存在一个相同的名字则返回
if (re.numRecords() > 0) {
Alert a_same = new Alert(BookConstant.alertTitle,
BookConstant.nameExistInfo,
null, AlertType.ERROR);
a_same.setTimeout(Alert.FOREVER);
Display.getDisplay(mid).setCurrent(a_same);
re.destroy();
return;
}
//添加一个新记录
BookAccount account = new BookAccount(nameField.getString(),
mobileField.getString(),
emailField.getString(),
phoneField.getString());
try {
byte[] rec = account.serialize();
rs.addRecord(rec, 0, rec.length);
Display.getDisplay(mid).setCurrent(dis);
}
catch (Exception e) {
}
}
}
else if (c == backCommand) {
Display.getDisplay(mid).setCurrent(dis);
}
}
}

package phonebook;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;
public class EditDetailInfo extends Form implements CommandListener {
private StringItem nameField;
private TextField mobileField;
private TextField phoneField;
private TextField emailField;
private Displayable dis;
private MIDlet mid;
private RecordStore rs = null;
private int recordID;
private static final Command saveCommand =
new Command(BookConstant.CmdSaveLabel, Command.OK, 2);
private static final Command backCommand =
new Command(BookConstant.CmdBackLabel, Command.BACK,3);
public EditDetailInfo(String title,
Displayable dis,
MIDlet mid,
RecordStore rs,
String name) {
super(title);
this.dis = dis;
this.mid = mid;
this.rs = rs;
nameField = new StringItem(BookConstant.name, name);
mobileField = new TextField(BookConstant.mobile, null, 25,
TextField.PHONENUMBER);
phoneField = new TextField(BookConstant.phone, null, 25,
TextField.PHONENUMBER);
emailField = new TextField(BookConstant.email, null, 25,
TextField.EMAILADDR);
this.append(nameField);
this.append(mobileField);
this.append(phoneField);
this.append(emailField);
RecordFilter rf = new FindFilter(name);
RecordEnumeration re = null;
try {
re = rs.enumerateRecords(rf, null, false);
}
catch (Exception e) {
}
//查找成功
if (re.numRecords() > 0) {
BookAccount account = null;
try {
byte[] rec;
recordID = re.nextRecordId();
rec = rs.getRecord(recordID);
account = BookAccount.deserialize(rec);
//nameField.setString(account.getUserName());
mobileField.setString(account.getMobilePhone());
phoneField.setString(account.getPhone());
emailField.setString(account.getEmail());
account = null;
re.destroy();
}
catch (Exception e) {
account = null;
System.out.println(“error”);
}
}
this.addCommand(saveCommand);
this.addCommand(backCommand);
this.setCommandListener(this);
}
public void commandAction(Command c, Displayable d) {
if (c == saveCommand) {
if (rs != null) {
//添加一个新记录
BookAccount account =
new BookAccount(nameField.getText(),
mobileField.getString(),
emailField.getString(),
phoneField.getString());
try {
byte[] rec = account.serialize();
rs.setRecord(recordID, rec, 0, rec.length);
Display.getDisplay(mid).setCurrent(dis);
}
catch (Exception e) {   }
}
}
else if (c == backCommand) {
Display.getDisplay(mid).setCurrent(dis);
}
}
}

package phonebook;
import java.util.Vector;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.rms.*;
public class DeleteRecord extends List implements CommandListener {
private Displayable dis;
private MIDlet mid;
private RecordStore rs = null;
private RecordEnumeration re = null;
private Vector recordIDs = null;
private int count = 0;
private static final Command deleteCommand =
new Command(BookConstant.CmdDelLabel, Command.OK,1);
private static final Command backCommand =
new Command(BookConstant.CmdBackLabel, Command.BACK,2);
public DeleteRecord(Displayable dis, MIDlet mid, RecordStore rs) {
super(BookConstant.DelTitle, Choice.MULTIPLE);
this.dis = dis;
this.mid = mid;
this.rs = rs;
this.addCommand(backCommand);
this.addCommand(deleteCommand);
this.setCommandListener(this);
recordIDs = new Vector();
SortComparator sortCom = new SortComparator();
if (rs != null) {
try {
Image icon = Image.createImage(“/res/txt.png”);
//按照名字的字符串大小排序
re = rs.enumerateRecords(null, sortCom, true);
//添加列表项
byte[] rec;
int id;
while (re.hasNextElement()) {
count = count + 1;
id = re.nextRecordId();
recordIDs.addElement(new Integer(id));
rec = rs.getRecord(id);
//分解数据库记录数据
BookAccount account = BookAccount.deserialize(rec);
//把名字添加到列表中
int index = this.append(account.getUserName(), icon);
}
}
catch (Exception e) {
}
finally {
if (re != null)
re.destroy();
}
}
}
public void commandAction(Command c, Displayable d) {
if (c == backCommand) {
Display.getDisplay(mid).setCurrent(dis);
}
if (c == deleteCommand) {
if (count == 0)
return;
//进入记录编辑界面
boolean[] selectedArray = new boolean[count];
this.getSelectedFlags(selectedArray);
int i = 0, j = 0;
for (i = 0; i < count; i++)
if (selectedArray[i] == true) {
if (!recordIDs.isEmpty()) {
j = ( (Integer) recordIDs.elementAt(i)).intValue();
try {
rs.deleteRecord(j);
Display.getDisplay(mid).setCurrent(dis);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
www.pdf24.org    发送文章为PDF   

J2ME通讯簿实例》上有9条评论

  1. 您应该是南大的万老师吧,看到J2ME就猜到是不是您了,哈哈

    听您的课受益匪浅,老师教师节快乐!

    可以关注一下android 和 iphone的手机开发

发表评论