Method insertContact
(Fig. 8.53) inserts a new contact with the given information into the database. We first put each piece of contact information into a new ContentValues object (lines 47–54), which maintains a map of key–value pairs—the database’s column names are the keys. Lines 56–58 open the database, insert the new contact and close the database. SQLiteDatabase
’s insert method (line 57) inserts the values from the given ContentValues
into the table specified as the first argument—the "contacts"
table in this case. The second parameter of this method, which is not used in this app, is named nullColumnHack
and is needed because SQLite does not support inserting a completely empty row into a table—this would be the equivalent of passing an empty ContentValues
object to insert
. Instead of making it illegal to pass an empty ContentValues
to the method, the nullColumnHack
parameter is used to identify a column that accepts NULL
values.
43 // inserts a new contact in the database
44 public long insertContact(String name, String phone, String email,
45 String street, String city, String state, String zip)
46 {
47 ContentValues newContact = new ContentValues();
48 newContact.put("name", name);
49 newContact.put("phone", phone);
50 newContact.put("email", email);
51 newContact.put("street", street);
52 newContact.put("city", city);
53 newContact.put("state", state);
54 newContact.put("zip", zip);
55
56 open(); // open the database
57 long rowID = database.insert("contacts", null, newContact);
58 close(); // close the database
59 return rowID;
60 } // end method insertContact
61