Teams Winter 2011/team1/BlackBerry/Implement Edit Option
8. Implement Edit Student Option
8.1. In order to Implement the Edit Student menu option, firs we have to make sure that our Student class has all setters and getters we need, so we have to add the following methods to the Student
:
public String getFirstname(){
return this.firstName;
}
public String getLastName(){
return this.lastName;
}
public void setEmail(String email){
this.email = email;
}
public void setFirstName( String firstName){
this.firstName=firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
8.2. Then we should make sure that our StudentList class which extends SortedReadableList, can edit it's elements, so we have to add the following method to the class StudentList
:
void updateElement(Object oldElement, Object newElement){
doUpdate(oldElement,newElement);
}
8.3. Now we need to add edit menu option to our application, so we should add it to ViewStudentApp
class:
// Added for Edit Student
MenuItem editItem = new MenuItem(new StringProvider("Edit Student"), 300, 3);
editItem.setCommand(new Command(new CommandHandler(){
public void execute(ReadOnlyCommandMetadata metadata, Object context) {
// TODO Auto-generated method stub
}
}
));
If we are at the main screen of the application and press the menu button of our device we ca see the result:
8.4. So far we added the Edit Menu option to the app, but it will not work as we have to modify the execute() method of it's CommandHandler. We want to add a Modal Screen which has editable fields for student first name , last name and email, and Save and cancel Buttons. Here is the code to achieve that:
First we need a method in ViewStudentApp
class, which updates student list and refreshes the view:
void editListElement(Student studentOld, Student studentNew){
_studentList.elementUpdated(_studentList, studentOld, studentNew);
_keywordFilterField.updateList();
}
Then we need to modify the execute() method of the editItem's CommandHandler:
public void execute(ReadOnlyCommandMetadata metadata, Object context) {
// TODO Auto-generated method stub
Student studentOld = (Student) _keywordFilterField.getSelectedElement();
Student studentNew = studentOld; // we need to keep an unchanged copy of our student to pass it to editListElement method
String[] selections = {"Save","Cancel"};
Dialog editDialog = new Dialog("Edit Student", selections, null, 0, null);
EditField inputField1 = new EditField("First Name: ", studentOld.getFirstname());
editDialog.add(inputField1);
EditField inputField2 = new EditField("Last Name:",studentOld.getLastName());
editDialog.add(inputField2);
EditField inputField3 = new EditField("Email: ",studentOld.getEmail());
editDialog.add(inputField3);
if(editDialog.doModal() == 0) { // if Save Button is selected
studentNew.setFirstName(inputField1.getText());
studentNew.setLastName(inputField2.getText());
studentNew.setEmail(inputField3.getText());
editListElement(studentOld, studentNew);
}
}