: Beginning Android

Give and Take

Give and Take

Of course, content providers would be astonishingly weak if you couldnt add or remove data from them, only update what is there. Fortunately, content providers offer these abilities as well.

To insert data into a content provider, you have two options available on the ContentProvider interface (available through getContentProvider() to your activity):

Use insert() with a collection Uri and a ContentValues structure describing the initial set of data to put in the row

Use bulkInsert() with a collection Uri and an array of ContentValues structures to populate several rows at once

The insert() method returns a Uri for you to use for future operations on that new object. The bulkInsert() method returns the number of created rows; you would need to do a query to get back at the data you just inserted.

For example, here is a snippet of code from ConstantsBrowser to insert a new constant into the content provider, given a DialogWrapper that can provide access to the title and value of the constant:

private voidprocessAdd(DialogWrapper wrapper) {
ContentValues values =newContentValues(2);
values.put(Provider.Constants.TITLE, wrapper.getTitle());
values.put(Provider.Constants.VALUE, wrapper.getValue());
getContentResolver().insert(Provider.Constants.CONTENT_URI,
values);
constantsCursor.requery();
}

Since we already have an outstanding Cursor for the content providers contents, we call requery() on that to update the Cursors contents. This, in turn, will update any SimpleCursorAdapter you may have wrapping the Cursor and that will update any selection widgets (e.g., ListView) you have using the adapter.

To delete one or more rows from the content provider, use the delete() method on ContentResolver. This works akin to a SQL DELETE statement and takes three parameters:

1.A Uri representing the collection (or instance) you wish to update

2.A constraint statement, functioning like a SQL WHERE clause, to determine which rows should be updated

3.An optional set of parameters to bind into the constraint clause, replacing any ?s that appear there


: 0.941. /Cache: 3 / 0