Login     Sign Up
Cyril Sermon (@admin)
9 months ago
56 Views

Adding, Updating, and Deleting Content

To perform transactions on Content Providers, use the delete, update, and insert methods on the ContentResolver object.

Inserts

The Content Resolver offers two methods for inserting new records into your Content Provider — insert and bulkInsert. Both methods accept the URI of the item type you’re adding; where the for-mer takes a single new ContentValues object, the latter takes an array.

The simple insert method will return a URI to the newly added record, while bulkInsert returns the number of successfully added items.

The following code snippet shows how to use the insert and bulkInsert methods:

Create a new row of values to insert.

ContentValues newValues = new ContentValues();

Assign values for each row.

newValues.put(COLUMN_NAME, newValue); [ ... Repeat for each column ... ]

Uri myRowUri = getContentResolver().insert(MyProvider.CONTENT_URI,

newValues);

Create a new row of values to insert.

ContentValues[] valueArray = new ContentValues[5];

TODO: Create an array of new rows

int count = getContentResolver().bulkInsert(MyProvider.CONTENT_URI,

valueArray);

Deletes

To delete a single record using the Content Resolver, call delete, passing in the URI of the row you want to remove. Alternatively, you can specify a where clause to remove multiple rows. Both techniques are shown in the following snippet:

// Remove a specific row.

getContentResolver().delete(myRowUri, null, null);

Remove the first five rows. String where = “_id < 5”;

getContentResolver().delete(MyProvider.CONTENT_URI, where, null);

Updates

Updates to a Content Provider are handled using the update method on a Content Resolver. The update method takes the URI of the target Content Provider, a ContentValues object that maps col-umn names to updated values, and a where clause that specifies which rows to update.

When executed, every matching row in the where clause will be updated using the values in the Con-tent Values passed in and will return the number of successful updates.

Create a new row of values to insert.

ContentValues newValues = new ContentValues();

Create a replacement map, specifying which columns you want to

update, and what values to assign to each of them.

 newValues.put(COLUMN_NAME, newValue);

Apply to the first 5 rows.

String where = “_id < 5”;

getContentResolver().update(MyProvider.CONTENT_URI, newValues, where,

null);
#Coding