Inserting Records

So far we have talked about how to retrieve data from content providers using URIs. Let us turn our attention to inserts, updates, and deletes. Let us start with insert first.

Android uses a class called android.content.ContentValues to hold the values for a single record, which is to be inserted. ContentValues is a dictionary of key/value pairs, much like column names and their values. You insert records by first populating a record into ContentValues and then asking android.content.ContentResolver to insert that record using a URI.

Note You need to locate ContentResolver because at this level of abstraction, you are not asking a database to insert a record; instead, you are asking to insert a record into a provider identified by a URI. ContentResolver is responsible for resolving the URI reference to the right provider and then passing on the ContentValues object to that specific provider.

Here is an example of populating a single row of notes in ContentValues in preparation for an insert:

ContentValues values = new ContentValues(); values.put("title", "New note"); values.put("note","This is a new note");

//values object is now ready to be inserted

Although we have hard-coded the column names, you can use constants defined in your Notepad application instead. You can get a reference to ContentResolver by asking the Activity class:

ContentResolver contentResolver = activity.getContentResolver();

Now all you need is a URI to tell ContentResolver to insert the row. These URIs are defined in a class corresponding to the Notes table. In the Notepad example, this URI is


We can take this URI and the ContentValues we have, and make a call to insert the row:

Uri uri = contentResolver.insert(Notepad.Notes.CONTENT_URI, values);

This call returns a URI pointing to the newly inserted record. This returned URI would match the following structure:


0 0

Post a comment