/*
* 添加新记录
*/
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("保存", Command.OK, 2);
private static final Command backCommand = new Command("返回", 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("提醒", "姓名不能为空,请输入姓名",
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("提醒", "你输入的姓名已经存在,请输入其他名字",
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);
}
}
}