Wednesday, 30 January 2013

Load the Restaurant Into the Form | Android Tutorial pdf

Load the Restaurant Into the Form

In the case where we are editing an existing restaurant, we need to load that restaurant from the database, then load it into the DetailForm. Since we created a RestaurantHelper in onCreate(), we need to close it again, so add an onDestroy() implementation to DetailForm as follows:
@Override
public void onDestroy() {
super.onDestroy();
helper.close();
}

Now that we have a handle to the database, we need to load a restaurant given its ID. So, add the following method to RestaurantHelper:
public Cursor getById(String id) {
String[] args={id};
return(getReadableDatabase()
.rawQuery("SELECT _id, name, address, type, notes FROM restaurants
WHERE _ID=?",
args));
}

Then, add the following lines to the bottom of onCreate() in DetailForm, to load in the specified restaurant into the form if its ID was specified in the Intent:
if (restaurantId!=null) {
load();
}

The code snippet above references a load() method, which we need to add to DetailForm, based off of code originally in LunchList:
private void load() {
Cursor c=helper.getById(restaurantId);
c.moveToFirst();
name.setText(helper.getName(c));
address.setText(helper.getAddress(c));
notes.setText(helper.getNotes(c));
if (helper.getType(c).equals("sit_down")) {
types.check(R.id.sit_down);
}
else if (helper.getType(c).equals("take_out")) {
types.check(R.id.take_out);
}
else {
types.check(R.id.delivery);
}
c.close();
}

No comments: