Changes

Jump to: navigation, search

Implementing an Android Content Provider

2,006 bytes added, 17:52, 20 May 2013
Implementing the Content Provider query() Method
return cursor;
}
</pre>
 
== Implementing the Content Provider update() Method ==
 
The update() method of the content provider is called when changes are being requested to existing database table rows. The method is passed a URI, the new values in the form of a ContentValues object and the usual selection argument strings.
 
When called, the update() method would typically perform the following steps:
 
* Use the sUriMatcher to identify the URI type.
* Throw an exception if the URI is not valid.
* Obtain a reference to a writable instance of the underlying SQLite database.
* Perform the appropriate update operation on the database depending on the selection criteria and the URI type.
* Notify the content resolver of the database change.
* Return a count of the number of rows that were changed as a result of the update operation.
 
A general-purpose update() method, and the one we will use for this project, would read as follows:
 
<pre>
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
 
int uriType = sURIMatcher.match(uri);
SQLiteDatabase sqlDB = myDB.getWritableDatabase();
int rowsUpdated = 0;
 
switch (uriType) {
case PRODUCTS:
rowsUpdated = sqlDB.update(MyDBHandler.TABLE_PRODUCTS,
values,
selection,
selectionArgs);
break;
case PRODUCTS_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsUpdated = sqlDB.update(MyDBHandler.TABLE_PRODUCTS,
values,
MyDBHandler.COLUMN_ID + "=" + id,
null);
} else {
rowsUpdated = sqlDB.update(MyDBHandler.TABLE_PRODUCTS,
values,
MyDBHandler.COLUMN_ID + "=" + id
+ " and "
+ selection,
selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsUpdated;
}
</pre>
== Implementing the Content Provider update() Method ==

Navigation menu