Build 1.0_r1(from source)

android.content
Class SyncableContentProvider

java.lang.Object
  extended by android.content.ContentProvider
      extended by android.content.SyncableContentProvider
All Implemented Interfaces:
ComponentCallbacks

public abstract class SyncableContentProvider
extends ContentProvider

A specialization of the ContentProvider that centralizes functionality used by ContentProviders that are syncable. It also wraps calls to the ContentProvider inside of database transactions.


Nested Class Summary
 
Nested classes/interfaces inherited from class android.content.ContentProvider
ContentProvider.Transport
 
Field Summary
protected  SQLiteDatabase mDb
           
protected  SQLiteOpenHelper mOpenHelper
           
 
Constructor Summary
SyncableContentProvider(String dbName, int dbVersion, Uri contentUri)
          Initializes the SyncableContentProvider
 
Method Summary
protected  void bootstrapDatabase(SQLiteDatabase db)
          Override to create your schema and do anything else you need to do with a new database.
 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 ContentProvider.insert(android.net.Uri, android.content.ContentValues) on each of them.
 boolean changeRequiresLocalSync(Uri uri)
          Check if changes to this URI can be syncable changes.
 void close()
          Close resources that must be closed.
 int delete(Uri url, String selection, String[] selectionArgs)
          A request to delete one or more rows.
protected abstract  int deleteInternal(Uri url, String selection, String[] selectionArgs)
          Subclasses should override this instead of delete().
protected  void deleteRowsForRemovedAccounts(Map<String,Boolean> accounts, String table, String accountColumnName)
          A helper method to delete all rows whose account is not in the accounts map.
 boolean getContainsDiffs()
           
 SQLiteDatabase getDatabase()
           
protected  Iterable<? extends AbstractTableMerger> getMergers()
          Each subclass of this class should define a subclass of AbstractTableMerger for each table they wish to merge.
 String getSyncingAccount()
          The account of the most recent call to onSyncStart()
 SyncableContentProvider getTemporaryInstance()
          Get a non-persistent instance of this content provider.
 Uri insert(Uri url, ContentValues values)
          Implement this to insert a new row.
protected abstract  Uri insertInternal(Uri url, ContentValues values)
          Subclasses should override this instead of insert().
 boolean isMergeCancelled()
           
protected  boolean isTemporary()
          Returns true if this instance is a temporary content provider.
 void merge(SyncContext context, SyncableContentProvider diffs, TempProviderSyncResult result, SyncResult syncResult)
          Merge diffs from a sync source with this content provider.
protected  void onAccountsChanged(String[] accountsArray)
          Make sure that there are no entries for accounts that no longer exist
 boolean onCreate()
          Called when the provider is being started.
protected  void onDatabaseOpened(SQLiteDatabase db)
          Override to do anything (like cleanups or checks) you need to do after opening a database.
 void onSyncCanceled()
          Invoked when the active sync has been canceled.
 void onSyncStart(SyncContext context, String account)
          Called right before a sync is started.
 void onSyncStop(SyncContext context, boolean success)
          Called right after a sync is completed
 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.
protected abstract  Cursor queryInternal(Uri url, String[] projection, String selection, String[] selectionArgs, String sortOrder)
          Subclasses should override this instead of query().
 byte[] readSyncDataBytes(String account)
          Retrieves the SyncData bytes for the given account.
 void setContainsDiffs(boolean containsDiffs)
           
 int update(Uri url, ContentValues values, String selection, String[] selectionArgs)
          Update a content URI.
protected abstract  int updateInternal(Uri url, ContentValues values, String selection, String[] selectionArgs)
          Subclasses should override this instead of update().
protected abstract  boolean upgradeDatabase(SQLiteDatabase db, int oldVersion, int newVersion)
          Override to upgrade your database from an old version to the version you specified.
 void wipeAccount(String account)
          Called when the sync system determines that this provider should no longer contain records for the specified account.
 void writeSyncDataBytes(String account, byte[] data)
          Sets the SyncData bytes for the given account.
 
Methods inherited from class android.content.ContentProvider
attachInfo, coerceToLocalContentProvider, getContext, getIContentProvider, getReadPermission, getSyncAdapter, getType, getWritePermission, onConfigurationChanged, onLowMemory, openFile, openFileHelper, setReadPermission, setWritePermission
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

mOpenHelper

protected SQLiteOpenHelper mOpenHelper

mDb

protected SQLiteDatabase mDb
Constructor Detail

SyncableContentProvider

public SyncableContentProvider(String dbName,
                               int dbVersion,
                               Uri contentUri)
Initializes the SyncableContentProvider

Parameters:
dbName - the filename of the database
dbVersion - the current version of the database schema
contentUri - The base Uri of the syncable content in this provider
Method Detail

isTemporary

protected boolean isTemporary()
Description copied from class: ContentProvider
Returns true if this instance is a temporary content provider.

Overrides:
isTemporary in class ContentProvider
Returns:
true if this instance is a temporary content provider

close

public void close()
Close resources that must be closed. You must call this to properly release the resources used by the SyncableContentProvider.


bootstrapDatabase

protected void bootstrapDatabase(SQLiteDatabase db)
Override to create your schema and do anything else you need to do with a new database. This is run inside a transaction (so you don't need to use one). This method may not use getDatabase(), or call content provider methods, it must only use the database handle passed to it.


upgradeDatabase

protected abstract boolean upgradeDatabase(SQLiteDatabase db,
                                           int oldVersion,
                                           int newVersion)
Override to upgrade your database from an old version to the version you specified. Don't set the DB version, this will automatically be done after the method returns. This method may not use getDatabase(), or call content provider methods, it must only use the database handle passed to it.

Parameters:
oldVersion - version of the existing database
newVersion - current version to upgrade to
Returns:
true if the upgrade was lossless, false if it was lossy

onDatabaseOpened

protected void onDatabaseOpened(SQLiteDatabase db)
Override to do anything (like cleanups or checks) you need to do after opening a database. Does nothing by default. This is run inside a transaction (so you don't need to use one). This method may not use getDatabase(), or call content provider methods, it must only use the database handle passed to it.


onCreate

public boolean onCreate()
Description copied from class: ContentProvider
Called when the provider is being started.

Specified by:
onCreate in class ContentProvider
Returns:
true if the provider was successfully loaded, false otherwise

getTemporaryInstance

public SyncableContentProvider getTemporaryInstance()
Get a non-persistent instance of this content provider. You must call close() on the returned SyncableContentProvider when you are done with it.

Returns:
a non-persistent content provider with the same layout as this provider.

getDatabase

public SQLiteDatabase getDatabase()

getContainsDiffs

public boolean getContainsDiffs()

setContainsDiffs

public void setContainsDiffs(boolean containsDiffs)

getMergers

protected Iterable<? extends AbstractTableMerger> 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:
A sequence of subclasses of AbstractTableMerger, one for each table that should be merged.

update

public final int update(Uri url,
                        ContentValues values,
                        String selection,
                        String[] selectionArgs)
Description copied from class: ContentProvider
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. This method can be called from multiple threads, as described in the Threading section of the Application Model overview.

Specified by:
update in class ContentProvider
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.
Returns:
the number of rows affected.

delete

public final int delete(Uri url,
                        String selection,
                        String[] selectionArgs)
Description copied from class: ContentProvider
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. This method can be called from multiple threads, as described in the Threading section of the Application Model overview.

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.

Specified by:
delete in class ContentProvider
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.
Returns:
The number of rows affected.

insert

public final Uri insert(Uri url,
                        ContentValues values)
Description copied from class: ContentProvider
Implement this to insert a new row. As a courtesy, call notifyChange() after inserting. This method can be called from multiple threads, as described in the Threading section of the Application Model overview.

Specified by:
insert in class ContentProvider
Parameters:
url - The content:// URI of the insertion request.
values - A set of column_name/value pairs to add to the database.
Returns:
The URI for the newly inserted item.

bulkInsert

public final int bulkInsert(Uri uri,
                            ContentValues[] values)
Description copied from class: ContentProvider
Implement this to insert a set of new rows, or the default implementation will iterate over the values and call ContentProvider.insert(android.net.Uri, android.content.ContentValues) on each of them. As a courtesy, call notifyChange() after inserting. This method can be called from multiple threads, as described in the Threading section of the Application Model overview.

Overrides:
bulkInsert in class ContentProvider
Parameters:
uri - The content:// URI of the insertion request.
values - An array of sets of column_name/value pairs to add to the database.
Returns:
The number of values that were inserted.

changeRequiresLocalSync

public boolean changeRequiresLocalSync(Uri uri)
Check if changes to this URI can be syncable changes.

Parameters:
uri - the URI of the resource that was changed
Returns:
true if changes to this URI can be syncable changes, false otherwise

query

public final Cursor query(Uri url,
                          String[] projection,
                          String selection,
                          String[] selectionArgs,
                          String sortOrder)
Description copied from class: ContentProvider
Receives a query request from a client in a local process, and returns a Cursor. This is called internally by the ContentResolver. This method can be called from multiple threads, as described in the Threading section of the Application Model overview.

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;

Specified by:
query in class ContentProvider
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.
Returns:
a Cursor or null.

onSyncStart

public void onSyncStart(SyncContext context,
                        String account)
Called right before a sync is started.

Parameters:
context - the sync context for the operation
account -

onSyncStop

public void onSyncStop(SyncContext context,
                       boolean success)
Called right after a sync is completed

Parameters:
context - the sync context for the operation
success - true if the sync succeeded, false if an error occurred

getSyncingAccount

public String getSyncingAccount()
The account of the most recent call to onSyncStart()

Returns:
the account

merge

public void merge(SyncContext context,
                  SyncableContentProvider diffs,
                  TempProviderSyncResult result,
                  SyncResult syncResult)
Merge diffs from a sync source with this content provider.

Parameters:
context - the SyncContext within which this merge is taking place
diffs - A temporary content provider containing diffs from a sync source.
result - a MergeResult that contains information about the merge, including a temporary content provider with the same layout as this provider containing
syncResult -

onSyncCanceled

public void onSyncCanceled()
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.


isMergeCancelled

public boolean isMergeCancelled()

updateInternal

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;


deleteInternal

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;


insertInternal

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;


queryInternal

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.


onAccountsChanged

protected void onAccountsChanged(String[] accountsArray)
Make sure that there are no entries for accounts that no longer exist

Parameters:
accountsArray - the array of currently-existing accounts

deleteRowsForRemovedAccounts

protected void deleteRowsForRemovedAccounts(Map<String,Boolean> 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.

wipeAccount

public void wipeAccount(String account)
Called when the sync system determines that this provider should no longer contain records for the specified account.


readSyncDataBytes

public byte[] readSyncDataBytes(String account)
Retrieves the SyncData bytes for the given account. The byte array returned may be null.


writeSyncDataBytes

public void writeSyncDataBytes(String account,
                               byte[] data)
Sets the SyncData bytes for the given account. The bytes array may be null.


Build 1.0_r1(from source)

Please submit a feedback, bug or feature