14.01.2013 Views

Android™ Application Development - Bahar Ali Khan

Android™ Application Development - Bahar Ali Khan

Android™ Application Development - Bahar Ali Khan

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Adding, Updating, and Deleting Content<br />

Chapter 6: Data Storage, Retrieval, and Sharing<br />

To perform transactions on Content Providers, use the delete, update, and insert methods on the<br />

ContentResolver object.<br />

Inserts<br />

The Content Resolver offers two methods for inserting new records into your Content Provider —<br />

insert and bulkInsert. Both methods accept the URI of the item type you’re adding; where the former<br />

takes a single new ContentValues object, the latter takes an array.<br />

The simple insert method will return a URI to the newly added record, while bulkInsert returns the<br />

number of successfully added items.<br />

The following code snippet shows how to use the insert and bulkInsert methods:<br />

Deletes<br />

// Create a new row of values to insert.<br />

ContentValues newValues = new ContentValues();<br />

// Assign values for each row.<br />

newValues.put(COLUMN_NAME, newValue);<br />

[ ... Repeat for each column ... ]<br />

Uri myRowUri = getContentResolver().insert(MyProvider.CONTENT_URI,<br />

newValues);<br />

// Create a new row of values to insert.<br />

ContentValues[] valueArray = new ContentValues[5];<br />

// TODO: Create an array of new rows<br />

int count = getContentResolver().bulkInsert(MyProvider.CONTENT_URI,<br />

valueArray);<br />

To delete a single record using the Content Resolver, call delete, passing in the URI of the row you<br />

want to remove. Alternatively, you can specify a where clause to remove multiple rows. Both techniques<br />

are shown in the following snippet:<br />

Updates<br />

// Remove a specific row.<br />

getContentResolver().delete(myRowUri, null, null);<br />

// Remove the first five rows.<br />

String where = “_id < 5”;<br />

getContentResolver().delete(MyProvider.CONTENT_URI, where, null);<br />

Updates to a Content Provider are handled using the update method on a Content Resolver. The<br />

update method takes the URI of the target Content Provider, a ContentValues object that maps column<br />

names to updated values, and a where clause that specifi es which rows to update.<br />

191

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!