Android Tutorial

(avery) #1
Android Tutorial 339

ContentValues values = new ContentValues();
values.put(Contacts.People.NAME, “Sample User”);
Uri uri = getContentResolver().insert(
Contacts.People.CONTENT_URI, values);
Uri phoneUri = Uri.withAppendedPath(uri,
Contacts.People.Phones.CONTENT_DIRECTORY);
values.clear();
values.put(Contacts.Phones.NUMBER, “2125551212”);
values.put(Contacts.Phones.TYPE, Contacts.Phones.TYPE_WORK);
getContentResolver().insert(phoneUri, values);
values.clear();
values.put(Contacts.Phones.NUMBER, “3135551212”);
values.put(Contacts.Phones.TYPE, Contacts.Phones.TYPE_MOBILE);
getContentResolver().insert(phoneUri, values);


Just as we used the ContentValues class to insert records into an
application’s SQLite database,we use it again here. The first action
we take is to provide a name for the Contacts.People.NAME
column. We need to create the contact with a name before we can
assign information, such as phone numbers. Think of this as
creating a row in a table that provides a one-to-many relationship
to a phone number table.

Next, we insert the data in the database found at the
Contacts.People.CONTENT_URI path. We use a call to
getContentResolver() to retrieve the ContentResolver associated
with our Activity. The return value is the Uri of our new contact. We
need to use it for adding phone numbers to our new contact. We
then reuse the ContentValues instance by clearing it and adding a
Contacts.Phones.NUMBER and the Contacts.Phones.TYPE for it.
Using the ContentResolver,we insert this data into the newly
created Uri.
Free download pdf