English | Site Directory

Android - An Open Handset Alliance Project

android.content
public abstract class

android.content.DatabaseContentProvider

java.lang.Object
android.content.ContentProvider
android.content.DatabaseContentProvider

A specialization of the ContentProvider that centralizes functionality used by ContentProviders that use the database, including controlling access to the database via the use of database transactions and java locks.

Nested Classes
DatabaseContentProvider.DcpCursor A specialization of SQLiteCursor that protects commitUpdates with a lock. 

Summary

Fields

protected      SQLiteDatabase  mDb   

Public Constructors

          DatabaseContentProvider(String dbName, int dbVersion)
Initializes the DatabaseContentProvider

Public Methods

        void  acquireDbLock()
Increments the hold count on the database lock for this thread, waiting for it to be released if another thread is already holding the lock.
    final    int  bulkInsert(Uri uri, ContentValues[] values)
Implement this to insert a set of new rows, or the default implementation will iterate over the values and call insert(Uri, ContentValues) on each of them.
        boolean  dbLockIsContended()
Checks if other threads are blocked on this lock.
    final    int  delete(Uri url, String selection, String[] selectionArgs)
A request to delete one or more rows.
        SQLiteDatabase  getDatabase()
        ContentProvider  getTemporaryInstance()
Get a non-persistent instance of this content provider.
    final    Uri  insert(Uri url, ContentValues values)
Implement this to insert a new row.
        boolean  isDbLockedByCurrentThread()
Checks if the database lock is held by this thread.
        boolean  isDbLockedByOtherThreads()
Checks if the database is locked by another thread.
        MergeResult  merge(SyncContext context, ContentProvider diffs, boolean readOnly)
Merge diffs from a sync source with this content provider.
        boolean  onCreate()
Called when the provider is being started.
        void  onSyncCancelled()
Invoked when the active sync has been canceled.
    final    Cursor  query(Uri url, String[] projection, String selection, String[] selectionArgs, String sortOrder)
Receives a query request from a client in a local process, and returns a Cursor.
        void  releaseDbLock(boolean success)
Decrement this thread's hold count on the database lock.
    final    int  update(Uri url, ContentValues values, String selection, String[] selectionArgs)
Update a content URI.

Protected Methods

        void  bootstrapDatabase()
abstract        int  deleteInternal(Uri url, String selection, String[] selectionArgs)
Subclasses should override this instead of delete().
        void  deleteRowsForRemovedAccounts(Map accounts, String table, String accountColumnName)
A helper method to delete all rows whose account is not in the accounts map.
        void  doDatabaseCleanup(String[] accountsArray)
make sure that there are no entries for accounts that no longer exist
        CursorFactory  getCursorFactory()
An accessor for the DcpCursorFactory.
        Iterable  getMergers()
Each subclass of this class should define a subclass of AbstractTableMerger for each table they wish to merge.
abstract        Uri  insertInternal(Uri url, ContentValues values)
Subclasses should override this instead of insert().
        boolean  isTemporary()
Returns true if this instance is a temporary content provider.
        Rt  lockAndCall(Callable callable)
Wraps a call to call() in a database acquire/release block.
        void  lockAndRun(Runnable runnable)
Wraps a call to run() in a database acquire/release block.
        void  onAccountsChanged(String[] accounts)
This is invoked at provider startup and when the set of active accounts changes.
        void  onDatabaseOpened()
abstract        Cursor  queryInternal(Uri url, String[] projection, String selection, String[] selectionArgs, String sortOrder)
Subclasses should override this instead of query().
abstract        int  updateInternal(Uri url, ContentValues values, String selection, String[] selectionArgs)
Subclasses should override this instead of update().
abstract        void  upgradeDatabase(int oldVersion, int newVersion)
Methods inherited from class android.content.ContentProvider
Methods inherited from class java.lang.Object

Details

Fields

protected SQLiteDatabase mDb

Public Constructors

public DatabaseContentProvider(String dbName, int dbVersion)

Initializes the DatabaseContentProvider

Parameters

dbName the filename of the database
dbVersion the current version of the database schema

Public Methods

public void acquireDbLock()

Increments the hold count on the database lock for this thread, waiting for it to be released if another thread is already holding the lock. If this thread didn't already hold the database lock then a database transaction will be started. The transaction will be committed or rolled back when the last releaseDbLock() for this thread is called.

public final int bulkInsert(Uri uri, ContentValues[] values)

Implement this to insert a set of new rows, or the default implementation will iterate over the values and call insert(Uri, ContentValues) on each of them. As a courtesy, call notifyChange() after inserting.

Parameters

uri The content:// URI of the insertion request.
values An array of sets of column_name/value pairs to add to the database.

public boolean dbLockIsContended()

Checks if other threads are blocked on this lock. This is typically used when the db is locked to tell if other threads are waiting to acquire the db lock.

Returns

  • true if other threads are waiting to acquire the db lock

public final int delete(Uri url, String selection, String[] selectionArgs)

A request to delete one or more rows. The selection clause is applied when performing the deletion, allowing the operation to affect multiple rows in a directory. As a courtesy, call notifyDelete() after deleting. The implementation is responsible for parsing out a row ID at the end of the URI, if a specific row is being deleted. That is, the client would pass in content://contacts/people/22 and the implementation is responsible for parsing the record number (22) when creating a SQL statement.

Parameters

url The full URI to query, including a row ID (if a specific record is requested).
selection An optional restriction to apply to rows when deleting.

public SQLiteDatabase getDatabase()

public ContentProvider getTemporaryInstance()

Get a non-persistent instance of this content provider. This is intended for use by the sync system, and is only required to be implemented if isSyncable() returns true.

public final Uri insert(Uri url, ContentValues values)

Implement this to insert a new row. As a courtesy, call notifyChange() after inserting.

Parameters

url The content:// URI of the insertion request.
values A set of column_name/value pairs to add to the database.

public boolean isDbLockedByCurrentThread()

Checks if the database lock is held by this thread.

Returns

  • true, if this thread is holding the database lock.

public boolean isDbLockedByOtherThreads()

Checks if the database is locked by another thread. This is just an estimate, since this status can change at any time, including after the call is made but before the result has been acted upon.

Returns

  • true, if the database is locked by another thread

public MergeResult merge(SyncContext context, ContentProvider diffs, boolean readOnly)

Merge diffs from a sync source with this content provider. This is intended for use by the sync system, and is only required to be implemented if isSyncable() returns true and this content provider is persistent.

Parameters

context the SyncContext within which this merge is taking place
diffs A temporary content provider containing diffs from a sync source.
readOnly if set then this merge should not return any local changes to sync up to the server.

public boolean onCreate()

Called when the provider is being started.

public void onSyncCancelled()

Invoked when the active sync has been canceled. The default implementation doesn't do anything (except ensure that this provider is syncable). Subclasses of ContentProvider that support canceling of sync should override this.

public final Cursor query(Uri url, String[] projection, String selection, String[] selectionArgs, String sortOrder)

Receives a query request from a client in a local process, and returns a Cursor. This is called internally by the ContentResolver.

Example client call:

// Request a specific record.
 Cursor managedCursor = managedQuery(
                Contacts.People.CONTENT_URI.addId(2),
                projection,    // Which columns to return.
                null,          // WHERE clause.
                People.NAME + " ASC");   // Sort order.
Example implementation:

// SQLiteQueryBuilder is a helper class that creates the
        // proper SQL syntax for us.
        SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();

        // Set the table we're querying.
        qBuilder.setTables(DATABASE_TABLE_NAME);

        // If the query ends in a specific record number, we're
        // being asked for a specific record, so set the
        // WHERE clause in our query.
        if((URI_MATCHER.match(uri)) == SPECIFIC_MESSAGE){
            qBuilder.appendWhere("_id=" + uri.getPathLeafId());
        }

        // Make the query.
        Cursor c = qBuilder.query(mDb,
                projection,
                selection,
                selectionArgs,
                groupBy,
                having,
                sortOrder);
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;

Parameters

url The URI to query. This will be the full URI sent by the client; if the client is requesting a specific record, the URI will end in a record number that the implementation should parse and add to a WHERE or HAVING clause, specifying that _id value.
projection The list of columns to put into the cursor. If null all columns are included.
selection A selection criteria to apply when filtering rows. If null then all rows are included.
sortOrder How the rows in the cursor should be sorted. If null then the provider is free to define the sort order.

public void releaseDbLock(boolean success)

Decrement this thread's hold count on the database lock. If this will cause the thread to be released, then prior to decrementing the hold count the database transaction will be either committed if this and all previous calls to releaseDbLock for this lock were passed success=true or the transaction will be rolled back and a SQLException thrown.

Parameters

success true, if the database actions that were made prior to this call should be committed, otherwise they will be rolled back

Throws

SQLException if the transaction is rolled back

public final int update(Uri url, ContentValues values, String selection, String[] selectionArgs)

Update a content URI. All rows matching the optionally provided selection will have their columns listed as the keys in the values map with the values of those keys. As a courtesy, call notifyChange() after updating.

Parameters

url The URI to query. This can potentially have a record ID if this is an update request for a specific record.
values A Bundle mapping from column names to new column values (NULL is a valid value).
selection An optional filter to match rows to update.

Protected Methods

protected void bootstrapDatabase()

protected abstract int deleteInternal(Uri url, String selection, String[] selectionArgs)

Subclasses should override this instead of delete(). See delete() for details.

This method is called within a acquireDbLock()/releaseDbLock() block, which means a database transaction will be active during the call;

protected void deleteRowsForRemovedAccounts(Map accounts, String table, String accountColumnName)

A helper method to delete all rows whose account is not in the accounts map. The accountColumnName is the name of the column that is expected to hold the account. If a row has an empty account it is never deleted.

Parameters

accounts a map of existing accounts
table the table to delete from
accountColumnName the name of the column that is expected to hold the account.

protected void doDatabaseCleanup(String[] accountsArray)

make sure that there are no entries for accounts that no longer exist

protected CursorFactory getCursorFactory()

An accessor for the DcpCursorFactory. This must be used by classes that extend DatabaseContentProvider when they open their real (not temporary) databases.

Returns

  • a CursorFactory

protected Iterable getMergers()

Each subclass of this class should define a subclass of AbstractTableMerger for each table they wish to merge. It should then override this method and return one instance of each merger, in sequence. Their merge methods will be called, one at a time, in the order supplied.

The default implementation returns an empty list, so that no merging will occur.

Returns

protected abstract Uri insertInternal(Uri url, ContentValues values)

Subclasses should override this instead of insert(). See insert() for details.

This method is called within a acquireDbLock()/releaseDbLock() block, which means a database transaction will be active during the call;

protected boolean isTemporary()

Returns true if this instance is a temporary content provider.

protected Rt lockAndCall(Callable callable)

Wraps a call to call() in a database acquire/release block. If an exception is caught during the call then the transaction will be marked as tainted, meaning it will be rolled back when the transaction is finally closed. This thread may already be running within a transaction, so this call to releaseDbLock(boolean) may not actually result in the transaction being closed.

If you don't require a return value, use lockAndRun(Runnable).

Parameters

callable the Callable to invoke.

Returns

  • the return value from Callable.call()

protected void lockAndRun(Runnable runnable)

Wraps a call to run() in a database acquire/release block. If an exception is caught during the call then the transaction will be marked as tainted, meaning it will be rolled back when the transaction is finally closed. This thread may already be running within a transaction, so this call to releaseDbLock(boolean) may not actually result in the transaction being closed.

If you need to return a value value, use lockAndCall(Callable).

Parameters

runnable the Runnable to invoke.

protected void onAccountsChanged(String[] accounts)

This is invoked at provider startup and when the set of active accounts changes.

Parameters

accounts the existing accounts

protected void onDatabaseOpened()

protected abstract Cursor queryInternal(Uri url, String[] projection, String selection, String[] selectionArgs, String sortOrder)

Subclasses should override this instead of query(). See query() for details.

This method is *not* called within a acquireDbLock()/releaseDbLock() block for performance reasons. If an implementation needs atomic access to the database the lock can be acquired then.

protected abstract int updateInternal(Uri url, ContentValues values, String selection, String[] selectionArgs)

Subclasses should override this instead of update(). See update() for details.

This method is called within a acquireDbLock()/releaseDbLock() block, which means a database transaction will be active during the call;

protected abstract void upgradeDatabase(int oldVersion, int newVersion)

Build m5-rc15g - 14 May 2008 12:50