Skip to content

Most visited

Recently visited

navigation

ContentResolver

public abstract class ContentResolver
extends Object

java.lang.Object
   ↳ android.content.ContentResolver
Known Direct Subclasses


This class provides applications access to the content model.

Developer Guides

For more information about using a ContentResolver with content providers, read the Content Providers developer guide.

Summary

Constants

String ANY_CURSOR_ITEM_TYPE

This is the Android platform's generic MIME type to match any MIME type of the form "CURSOR_ITEM_BASE_TYPE/SUB_TYPE".

String CURSOR_DIR_BASE_TYPE

This is the Android platform's base MIME type for a content: URI containing a Cursor of zero or more items.

String CURSOR_ITEM_BASE_TYPE

This is the Android platform's base MIME type for a content: URI containing a Cursor of a single item.

String EXTRA_HONORED_ARGS

Allows provider to report back to client which keys were honored.

String EXTRA_REFRESH_SUPPORTED

An extra boolean describing whether a particular provider supports refresh or not.

String EXTRA_SIZE

An extra Point describing the optimal size for a requested image resource, in pixels.

String EXTRA_TOTAL_SIZE

Added to Cursor extras Bundle to indicate total size of recordset when paging is active.

int NOTIFY_SKIP_NOTIFY_FOR_DESCENDANTS

Flag for notifyChange(Uri, ContentObserver, int): if set, this notification will be skipped if it is being delivered to the root URI of a ContentObserver that is using "notify for descendants." The purpose of this is to allow the provide to send a general notification of "something under X" changed that observers of that specific URI can receive, while also sending a specific URI under X.

int NOTIFY_SYNC_TO_NETWORK

Flag for notifyChange(Uri, ContentObserver, int): attempt to sync the change to the network.

String QUERY_ARG_LIMIT

Specifies the max number of records to include in a recordset with respect to the starting offset, which by default is 0.

String QUERY_ARG_OFFSET

Specifies the offset from which to load a recordset.

String QUERY_ARG_SORT_COLLATION

Allows client to specify a hint to the provider as to which collation to use when sorting text values.

String QUERY_ARG_SORT_COLUMNS

Specifies the list of columns against which to sort results.

String QUERY_ARG_SORT_DIRECTION

Specifies desired sort order.

String QUERY_ARG_SQL_SELECTION

Key for an SQL style selection string that may be present in the query Bundle argument passed to query(Uri, String[], Bundle, CancellationSignal) when called by a legacy client.

String QUERY_ARG_SQL_SELECTION_ARGS

Key for SQL selection string arguments list.

String QUERY_ARG_SQL_SORT_ORDER

Key for an SQL style sort string that may be present in the query Bundle argument passed to query(Uri, String[], Bundle, CancellationSignal) when called by a legacy client.

int QUERY_SORT_DIRECTION_ASCENDING

int QUERY_SORT_DIRECTION_DESCENDING

String SCHEME_ANDROID_RESOURCE

String SCHEME_CONTENT

String SCHEME_FILE

String SYNC_EXTRAS_ACCOUNT

This constant was deprecated in API level 5. instead use requestSync(android.accounts.Account, String, android.os.Bundle)

String SYNC_EXTRAS_DISCARD_LOCAL_DELETIONS

Indicates that the sync adapter should not proceed with the delete operations, if it determines that there are too many.

String SYNC_EXTRAS_DO_NOT_RETRY

If this extra is set to true then the request will not be retried if it fails.

String SYNC_EXTRAS_EXPEDITED

If this extra is set to true, the sync request will be scheduled at the front of the sync request queue and without any delay

String SYNC_EXTRAS_FORCE

This constant was deprecated in API level 5. instead use SYNC_EXTRAS_MANUAL

String SYNC_EXTRAS_IGNORE_BACKOFF

If this extra is set to true then any backoffs for the initial attempt (e.g.

String SYNC_EXTRAS_IGNORE_SETTINGS

If this extra is set to true then the sync settings (like getSyncAutomatically()) are ignored by the sync scheduler.

String SYNC_EXTRAS_INITIALIZE

Set by the SyncManager to request that the SyncAdapter initialize itself for the given account/authority pair.

String SYNC_EXTRAS_MANUAL

Setting this extra is the equivalent of setting both SYNC_EXTRAS_IGNORE_SETTINGS and SYNC_EXTRAS_IGNORE_BACKOFF

String SYNC_EXTRAS_OVERRIDE_TOO_MANY_DELETIONS

Indicates that the sync adapter should proceed with the delete operations, even if it determines that there are too many.

String SYNC_EXTRAS_REQUIRE_CHARGING

If this extra is set to true, the sync request will be scheduled only when the device is plugged in.

String SYNC_EXTRAS_UPLOAD

Indicates that this sync is intended to only upload local changes to the server.

int SYNC_OBSERVER_TYPE_ACTIVE

int SYNC_OBSERVER_TYPE_PENDING

int SYNC_OBSERVER_TYPE_SETTINGS

Public constructors

ContentResolver(Context context)

Public methods

final ContentProviderClient acquireContentProviderClient(Uri uri)

Returns a ContentProviderClient that is associated with the ContentProvider that services the content at uri, starting the provider if necessary.

final ContentProviderClient acquireContentProviderClient(String name)

Returns a ContentProviderClient that is associated with the ContentProvider with the authority of name, starting the provider if necessary.

final ContentProviderClient acquireUnstableContentProviderClient(String name)

Like acquireContentProviderClient(String), but for use when you do not trust the stability of the target content provider.

final ContentProviderClient acquireUnstableContentProviderClient(Uri uri)

Like acquireContentProviderClient(Uri), but for use when you do not trust the stability of the target content provider.

static void addPeriodicSync(Account account, String authority, Bundle extras, long pollFrequency)

Specifies that a sync should be requested with the specified the account, authority, and extras at the given frequency.

static Object addStatusChangeListener(int mask, SyncStatusObserver callback)

Request notifications when the different aspects of the SyncManager change.

ContentProviderResult[] applyBatch(String authority, ArrayList<ContentProviderOperation> operations)

Applies each of the ContentProviderOperation objects and returns an array of their results.

final int bulkInsert(Uri url, ContentValues[] values)

Inserts multiple rows into a table at the given URL.

final Bundle call(Uri uri, String method, String arg, Bundle extras)

Call a provider-defined method.

void cancelSync(Uri uri)

This method was deprecated in API level 5. instead use cancelSync(android.accounts.Account, String)

static void cancelSync(SyncRequest request)

Remove the specified sync.

static void cancelSync(Account account, String authority)

Cancel any active or pending syncs that match account and authority.

final Uri canonicalize(Uri url)

Transform the given url to a canonical representation of its referenced resource, which can be used across devices, persisted, backed up and restored, etc.

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

Deletes row(s) specified by a content URI.

static SyncInfo getCurrentSync()

This method was deprecated in API level 11. Since multiple concurrent syncs are now supported you should use getCurrentSyncs() to get the accurate list of current syncs. This method returns the first item from the list of current syncs or null if there are none.

static List<SyncInfo> getCurrentSyncs()

Returns a list with information about all the active syncs.

static int getIsSyncable(Account account, String authority)

Check if this account/provider is syncable.

static boolean getMasterSyncAutomatically()

Gets the master auto-sync setting that applies to all the providers and accounts.

List<UriPermission> getOutgoingPersistedUriPermissions()

Return list of all persisted URI permission grants that are hosted by the calling app.

static List<PeriodicSync> getPeriodicSyncs(Account account, String authority)

Get the list of information about the periodic syncs for the given account and authority.

List<UriPermission> getPersistedUriPermissions()

Return list of all URI permission grants that have been persisted by the calling app.

String[] getStreamTypes(Uri url, String mimeTypeFilter)

Query for the possible MIME types for the representations the given content URL can be returned when opened as as stream with openTypedAssetFileDescriptor(Uri, String, Bundle).

static SyncAdapterType[] getSyncAdapterTypes()

Get information about the SyncAdapters that are known to the system.

static boolean getSyncAutomatically(Account account, String authority)

Check if the provider should be synced when a network tickle is received

This method requires the caller to hold the permission READ_SYNC_SETTINGS.

final String getType(Uri url)

Return the MIME type of the given content URL.

final Uri insert(Uri url, ContentValues values)

Inserts a row into a table at the given URL.

static boolean isSyncActive(Account account, String authority)

Returns true if there is currently a sync operation for the given account or authority actively being processed.

static boolean isSyncPending(Account account, String authority)

Return true if the pending status is true of any matching authorities.

void notifyChange(Uri uri, ContentObserver observer, boolean syncToNetwork)

Notify registered observers that a row was updated.

void notifyChange(Uri uri, ContentObserver observer, int flags)

Notify registered observers that a row was updated.

void notifyChange(Uri uri, ContentObserver observer)

Notify registered observers that a row was updated and attempt to sync changes to the network.

final AssetFileDescriptor openAssetFileDescriptor(Uri uri, String mode, CancellationSignal cancellationSignal)

Open a raw file descriptor to access data under a URI.

final AssetFileDescriptor openAssetFileDescriptor(Uri uri, String mode)

Open a raw file descriptor to access data under a URI.

final ParcelFileDescriptor openFileDescriptor(Uri uri, String mode, CancellationSignal cancellationSignal)

Open a raw file descriptor to access data under a URI.

final ParcelFileDescriptor openFileDescriptor(Uri uri, String mode)

Open a raw file descriptor to access data under a URI.

final InputStream openInputStream(Uri uri)

Open a stream on to the content associated with a content URI.

final OutputStream openOutputStream(Uri uri)

Synonym for openOutputStream(uri, "w").

final OutputStream openOutputStream(Uri uri, String mode)

Open a stream on to the content associated with a content URI.

final AssetFileDescriptor openTypedAssetFileDescriptor(Uri uri, String mimeType, Bundle opts, CancellationSignal cancellationSignal)

Open a raw file descriptor to access (potentially type transformed) data from a "content:" URI.

final AssetFileDescriptor openTypedAssetFileDescriptor(Uri uri, String mimeType, Bundle opts)

Open a raw file descriptor to access (potentially type transformed) data from a "content:" URI.

final Cursor query(Uri uri, String[] projection, Bundle queryArgs, CancellationSignal cancellationSignal)

Query the given URI, returning a Cursor over the result set with support for cancellation.

final Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, CancellationSignal cancellationSignal)

Query the given URI, returning a Cursor over the result set with optional support for cancellation.

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

Query the given URI, returning a Cursor over the result set.

final boolean refresh(Uri url, Bundle args, CancellationSignal cancellationSignal)

This allows clients to request an explicit refresh of content identified by uri.

final void registerContentObserver(Uri uri, boolean notifyForDescendants, ContentObserver observer)

Register an observer class that gets callbacks when data identified by a given content URI changes.

void releasePersistableUriPermission(Uri uri, int modeFlags)

Relinquish a persisted URI permission grant.

static void removePeriodicSync(Account account, String authority, Bundle extras)

Remove a periodic sync.

static void removeStatusChangeListener(Object handle)

Remove a previously registered status change listener.

static void requestSync(Account account, String authority, Bundle extras)

Start an asynchronous sync operation.

static void requestSync(SyncRequest request)

Register a sync with the SyncManager.

static void setIsSyncable(Account account, String authority, int syncable)

Set whether this account/provider is syncable.

static void setMasterSyncAutomatically(boolean sync)

Sets the master auto-sync setting that applies to all the providers and accounts.

static void setSyncAutomatically(Account account, String authority, boolean sync)

Set whether or not the provider is synced when it receives a network tickle.

void startSync(Uri uri, Bundle extras)

This method was deprecated in API level 5. instead use requestSync(android.accounts.Account, String, android.os.Bundle)

void takePersistableUriPermission(Uri uri, int modeFlags)

Take a persistable URI permission grant that has been offered.

final Uri uncanonicalize(Uri url)

Given a canonical Uri previously generated by canonicalize(Uri), convert it to its local non-canonical form.

final void unregisterContentObserver(ContentObserver observer)

Unregisters a change observer.

final int update(Uri uri, ContentValues values, String where, String[] selectionArgs)

Update row(s) in a content URI.

static void validateSyncExtrasBundle(Bundle extras)

Check that only values of the following types are in the Bundle:

  • Integer
  • Long
  • Boolean
  • Float
  • Double
  • String
  • Account
  • null

Inherited methods

From class java.lang.Object

Constants

ANY_CURSOR_ITEM_TYPE

added in API level 21
String ANY_CURSOR_ITEM_TYPE

This is the Android platform's generic MIME type to match any MIME type of the form "CURSOR_ITEM_BASE_TYPE/SUB_TYPE". SUB_TYPE is the sub-type of the application-dependent content, e.g., "audio", "video", "playlist".

Constant Value: "vnd.android.cursor.item/*"

CURSOR_DIR_BASE_TYPE

added in API level 1
String CURSOR_DIR_BASE_TYPE

This is the Android platform's base MIME type for a content: URI containing a Cursor of zero or more items. Applications should use this as the base type along with their own sub-type of their content: URIs that represent a directory of items. For example, hypothetical IMAP email client may have a URI content://com.company.provider.imap/inbox for all of the messages in its inbox, whose MIME type would be reported as CURSOR_DIR_BASE_TYPE + "/vnd.company.imap-msg"

Note how the base MIME type varies between this and CURSOR_ITEM_BASE_TYPE depending on whether there is one single item or multiple items in the data set, while the sub-type remains the same because in either case the data structure contained in the cursor is the same.

Constant Value: "vnd.android.cursor.dir"

CURSOR_ITEM_BASE_TYPE

added in API level 1
String CURSOR_ITEM_BASE_TYPE

This is the Android platform's base MIME type for a content: URI containing a Cursor of a single item. Applications should use this as the base type along with their own sub-type of their content: URIs that represent a particular item. For example, hypothetical IMAP email client may have a URI content://com.company.provider.imap/inbox/1 for a particular message in the inbox, whose MIME type would be reported as CURSOR_ITEM_BASE_TYPE + "/vnd.company.imap-msg"

Compare with CURSOR_DIR_BASE_TYPE.

Constant Value: "vnd.android.cursor.item"

EXTRA_HONORED_ARGS

String EXTRA_HONORED_ARGS

Allows provider to report back to client which keys were honored. Key identifying a String[] containing all QUERY_ARG_SORT* arguments honored by the provider. Include this in Cursor extras Bundle when any QUERY_ARG_SORT* value was honored during the preparation of the results Cursor.

Constant Value: "android.content.extra.HONORED_ARGS"

EXTRA_REFRESH_SUPPORTED

String EXTRA_REFRESH_SUPPORTED

An extra boolean describing whether a particular provider supports refresh or not. If a provider supports refresh, it should include this key in its returned Cursor as part of its query call.

Constant Value: "android.content.extra.REFRESH_SUPPORTED"

EXTRA_SIZE

added in API level 21
String EXTRA_SIZE

An extra Point describing the optimal size for a requested image resource, in pixels. If a provider has multiple sizes of the image, it should return the image closest to this size.

Constant Value: "android.content.extra.SIZE"

EXTRA_TOTAL_SIZE

String EXTRA_TOTAL_SIZE

Added to Cursor extras Bundle to indicate total size of recordset when paging is active. Providers must include this when implementing paging support.

When full size of the recordset is unknown a provider may return -1 to indicate this.

Providers having returned -1 in a previous query are recommended to send content change notification once (if) full recordset size becomes known.

Constant Value: "android.content.extra.TOTAL_SIZE"

NOTIFY_SKIP_NOTIFY_FOR_DESCENDANTS

added in API level 24
int NOTIFY_SKIP_NOTIFY_FOR_DESCENDANTS

Flag for notifyChange(Uri, ContentObserver, int): if set, this notification will be skipped if it is being delivered to the root URI of a ContentObserver that is using "notify for descendants." The purpose of this is to allow the provide to send a general notification of "something under X" changed that observers of that specific URI can receive, while also sending a specific URI under X. It would use this flag when sending the former, so that observers of "X and descendants" only see the latter.

Constant Value: 2 (0x00000002)

NOTIFY_SYNC_TO_NETWORK

added in API level 24
int NOTIFY_SYNC_TO_NETWORK

Flag for notifyChange(Uri, ContentObserver, int): attempt to sync the change to the network.

Constant Value: 1 (0x00000001)

QUERY_ARG_LIMIT

String QUERY_ARG_LIMIT

Specifies the max number of records to include in a recordset with respect to the starting offset, which by default is 0. Records beyond starting offset + limit should be omitted from results.

Providers are recommended to create a content notification Uri that encapsulates QUERY_ARG_OFFSET and QUERY_ARG_LIMITS values reflected in the recordset. This will allow a provider to notify clients of changes to an individual recordset.

Constant Value: "android:query-page-limit"

QUERY_ARG_OFFSET

String QUERY_ARG_OFFSET

Specifies the offset from which to load a recordset. Records prior to this position should be omitted from results.

Providers are recommended to create a content notification Uri that encapsulates QUERY_ARG_OFFSET and QUERY_ARG_LIMITS values reflected in the recordset. This will allow a provider to notify clients of changes to an individual recordset.

Constant Value: "android:query-page-offset"

QUERY_ARG_SORT_COLLATION

String QUERY_ARG_SORT_COLLATION

Allows client to specify a hint to the provider as to which collation to use when sorting text values.

Providers may provide their own collators. When selecting a custom collator the value will be determined by the Provider.

  • When supplying data using a ContentProvider, it is strongly recommended that an entry be included in the Cursor extras Bundle under this same key (@link QUERY_ARG_SORT_COLLATION}) to indicate that sort collation was applied to the recordset.

    When querying a provider, where no QUERY_ARG_SQL* otherwise exists in the arguments Bundle, the Content framework will attempt to synthesize an QUERY_ARG_SQL* argument using the corresponding QUERY_ARG_SORT* values.

    Constant Value: "android:query-sort-collation"

  • QUERY_ARG_SORT_COLUMNS

    String QUERY_ARG_SORT_COLUMNS

    Specifies the list of columns against which to sort results. When first column values are identical, records are then sorted based on second column values, and so on.

    Columns present in this list must also be included in the projection supplied to query(Uri, String[], Bundle, CancellationSignal).

    Apps targeting O or higher:

  • When supplying data using a ContentProvider, it is strongly recommended that an entry be included in the Cursor extras Bundle under this same key (@link QUERY_ARG_SORT_COLUMNS}) to indicate which column sorting was applied to the recordset, if any.
  • When querying a provider, where no QUERY_ARG_SQL* otherwise exists in the arguments Bundle, the Content framework will attempt to synthesize an QUERY_ARG_SQL* argument using the corresponding QUERY_ARG_SORT* values.

    Constant Value: "android:query-sort-columns"

  • QUERY_ARG_SORT_DIRECTION

    String QUERY_ARG_SORT_DIRECTION

    Specifies desired sort order. When unspecified a provider may provide a default sort direction, or choose to return unsorted results.

    Apps targeting O or higher:

  • When supplying data using a ContentProvider, it is strongly recommended that an entry be included in the Cursor extras Bundle under this same key (@link QUERY_ARG_SORT_DIRECTION}) to indicate that sort direction was applied to the recordset.
  • When querying a provider, where no QUERY_ARG_SQL* otherwise exists in the arguments Bundle, the Content framework will attempt to synthesize an QUERY_ARG_SQL* argument using the corresponding QUERY_ARG_SORT* values.

    Constant Value: "android:query-sort-direction"

  • QUERY_ARG_SQL_SELECTION

    String QUERY_ARG_SQL_SELECTION

    Key for an SQL style selection string that may be present in the query Bundle argument passed to query(Uri, String[], Bundle, CancellationSignal) when called by a legacy client.

    Clients should never include user supplied values directly in the selection string, as this presents an avenue for SQL injection attacks. In lieu of this, a client should use standard placeholder notation to represent values in a selection string, then supply a corresponding value in .QUERY_ARG_SQL_SELECTION_ARGS.

    Apps targeting O or higher are strongly encourage to use structured query arguments in lieu of opaque SQL query clauses. See: QUERY_ARG_SORT_COLUMNS, QUERY_ARG_SORT_DIRECTION, and QUERY_ARG_SORT_COLLATION.

    Constant Value: "android:query-sql-selection"

    QUERY_ARG_SQL_SELECTION_ARGS

    String QUERY_ARG_SQL_SELECTION_ARGS

    Key for SQL selection string arguments list.

    Clients should never include user supplied values directly in the selection string, as this presents an avenue for SQL injection attacks. In lieu of this, a client should use standard placeholder notation to represent values in a selection string, then supply a corresponding value in .QUERY_ARG_SQL_SELECTION_ARGS.

    Apps targeting O or higher are strongly encourage to use structured query arguments in lieu of opaque SQL query clauses. See: QUERY_ARG_SORT_COLUMNS, QUERY_ARG_SORT_DIRECTION, and QUERY_ARG_SORT_COLLATION.

    Constant Value: "android:query-sql-selection-args"

    QUERY_ARG_SQL_SORT_ORDER

    String QUERY_ARG_SQL_SORT_ORDER

    Key for an SQL style sort string that may be present in the query Bundle argument passed to query(Uri, String[], Bundle, CancellationSignal) when called by a legacy client.

    Apps targeting O or higher are strongly encourage to use structured query arguments in lieu of opaque SQL query clauses. See: QUERY_ARG_SORT_COLUMNS, QUERY_ARG_SORT_DIRECTION, and QUERY_ARG_SORT_COLLATION.

    Constant Value: "android:query-sql-sort-order"

    QUERY_SORT_DIRECTION_ASCENDING

    int QUERY_SORT_DIRECTION_ASCENDING

    Constant Value: 0 (0x00000000)

    QUERY_SORT_DIRECTION_DESCENDING

    int QUERY_SORT_DIRECTION_DESCENDING

    Constant Value: 1 (0x00000001)

    SCHEME_ANDROID_RESOURCE

    added in API level 1
    String SCHEME_ANDROID_RESOURCE

    Constant Value: "android.resource"

    SCHEME_CONTENT

    added in API level 1
    String SCHEME_CONTENT

    Constant Value: "content"

    SCHEME_FILE

    added in API level 1
    String SCHEME_FILE

    Constant Value: "file"

    SYNC_EXTRAS_ACCOUNT

    added in API level 1
    String SYNC_EXTRAS_ACCOUNT

    This constant was deprecated in API level 5.
    instead use requestSync(android.accounts.Account, String, android.os.Bundle)

    Constant Value: "account"

    SYNC_EXTRAS_DISCARD_LOCAL_DELETIONS

    added in API level 1
    String SYNC_EXTRAS_DISCARD_LOCAL_DELETIONS

    Indicates that the sync adapter should not proceed with the delete operations, if it determines that there are too many. See tooManyDeletions

    Constant Value: "discard_deletions"

    SYNC_EXTRAS_DO_NOT_RETRY

    added in API level 8
    String SYNC_EXTRAS_DO_NOT_RETRY

    If this extra is set to true then the request will not be retried if it fails.

    Constant Value: "do_not_retry"

    SYNC_EXTRAS_EXPEDITED

    added in API level 1
    String SYNC_EXTRAS_EXPEDITED

    If this extra is set to true, the sync request will be scheduled at the front of the sync request queue and without any delay

    Constant Value: "expedited"

    SYNC_EXTRAS_FORCE

    added in API level 1
    String SYNC_EXTRAS_FORCE

    This constant was deprecated in API level 5.
    instead use SYNC_EXTRAS_MANUAL

    Constant Value: "force"

    SYNC_EXTRAS_IGNORE_BACKOFF

    added in API level 8
    String SYNC_EXTRAS_IGNORE_BACKOFF

    If this extra is set to true then any backoffs for the initial attempt (e.g. due to retries) are ignored by the sync scheduler. If this request fails and gets rescheduled then the retries will still honor the backoff.

    Constant Value: "ignore_backoff"

    SYNC_EXTRAS_IGNORE_SETTINGS

    added in API level 8
    String SYNC_EXTRAS_IGNORE_SETTINGS

    If this extra is set to true then the sync settings (like getSyncAutomatically()) are ignored by the sync scheduler.

    Constant Value: "ignore_settings"

    SYNC_EXTRAS_INITIALIZE

    added in API level 5
    String SYNC_EXTRAS_INITIALIZE

    Set by the SyncManager to request that the SyncAdapter initialize itself for the given account/authority pair. One required initialization step is to ensure that setIsSyncable(android.accounts.Account, String, int) has been called with a >= 0 value. When this flag is set the SyncAdapter does not need to do a full sync, though it is allowed to do so.

    Constant Value: "initialize"

    SYNC_EXTRAS_MANUAL

    added in API level 5
    String SYNC_EXTRAS_MANUAL

    Setting this extra is the equivalent of setting both SYNC_EXTRAS_IGNORE_SETTINGS and SYNC_EXTRAS_IGNORE_BACKOFF

    Constant Value: "force"

    SYNC_EXTRAS_OVERRIDE_TOO_MANY_DELETIONS

    added in API level 1
    String SYNC_EXTRAS_OVERRIDE_TOO_MANY_DELETIONS

    Indicates that the sync adapter should proceed with the delete operations, even if it determines that there are too many. See tooManyDeletions

    Constant Value: "deletions_override"

    SYNC_EXTRAS_REQUIRE_CHARGING

    added in API level 24
    String SYNC_EXTRAS_REQUIRE_CHARGING

    If this extra is set to true, the sync request will be scheduled only when the device is plugged in. This is equivalent to calling setRequiresCharging(true) on SyncRequest.

    Constant Value: "require_charging"

    SYNC_EXTRAS_UPLOAD

    added in API level 1
    String SYNC_EXTRAS_UPLOAD

    Indicates that this sync is intended to only upload local changes to the server. For example, this will be set to true if the sync is initiated by a call to notifyChange(android.net.Uri, android.database.ContentObserver, boolean)

    Constant Value: "upload"

    SYNC_OBSERVER_TYPE_ACTIVE

    added in API level 8
    int SYNC_OBSERVER_TYPE_ACTIVE

    Constant Value: 4 (0x00000004)

    SYNC_OBSERVER_TYPE_PENDING

    added in API level 8
    int SYNC_OBSERVER_TYPE_PENDING

    Constant Value: 2 (0x00000002)

    SYNC_OBSERVER_TYPE_SETTINGS

    added in API level 8
    int SYNC_OBSERVER_TYPE_SETTINGS

    Constant Value: 1 (0x00000001)

    Public constructors

    ContentResolver

    added in API level 1
    ContentResolver (Context context)

    Parameters
    context Context

    Public methods

    acquireContentProviderClient

    added in API level 5
    ContentProviderClient acquireContentProviderClient (Uri uri)

    Returns a ContentProviderClient that is associated with the ContentProvider that services the content at uri, starting the provider if necessary. Returns null if there is no provider associated wih the uri. The caller must indicate that they are done with the provider by calling release() which will allow the system to release the provider it it determines that there is no other reason for keeping it active.

    Parameters
    uri Uri: specifies which provider should be acquired
    Returns
    ContentProviderClient a ContentProviderClient that is associated with the ContentProvider that services the content at uri or null if there isn't one.

    acquireContentProviderClient

    added in API level 5
    ContentProviderClient acquireContentProviderClient (String name)

    Returns a ContentProviderClient that is associated with the ContentProvider with the authority of name, starting the provider if necessary. Returns null if there is no provider associated wih the uri. The caller must indicate that they are done with the provider by calling release() which will allow the system to release the provider it it determines that there is no other reason for keeping it active.

    Parameters
    name String: specifies which provider should be acquired
    Returns
    ContentProviderClient a ContentProviderClient that is associated with the ContentProvider with the authority of name or null if there isn't one.

    acquireUnstableContentProviderClient

    added in API level 16
    ContentProviderClient acquireUnstableContentProviderClient (String name)

    Like acquireContentProviderClient(String), but for use when you do not trust the stability of the target content provider. This turns off the mechanism in the platform clean up processes that are dependent on a content provider if that content provider's process goes away. Normally you can safely assume that once you have acquired a provider, you can freely use it as needed and it won't disappear, even if your process is in the background. If using this method, you need to take care to deal with any failures when communicating with the provider, and be sure to close it so that it can be re-opened later. In particular, catching a DeadObjectException from the calls there will let you know that the content provider has gone away; at that point the current ContentProviderClient object is invalid, and you should release it. You can acquire a new one if you would like to try to restart the provider and perform new operations on it.

    Parameters
    name String
    Returns
    ContentProviderClient

    acquireUnstableContentProviderClient

    added in API level 16
    ContentProviderClient acquireUnstableContentProviderClient (Uri uri)

    Like acquireContentProviderClient(Uri), but for use when you do not trust the stability of the target content provider. This turns off the mechanism in the platform clean up processes that are dependent on a content provider if that content provider's process goes away. Normally you can safely assume that once you have acquired a provider, you can freely use it as needed and it won't disappear, even if your process is in the background. If using this method, you need to take care to deal with any failures when communicating with the provider, and be sure to close it so that it can be re-opened later. In particular, catching a DeadObjectException from the calls there will let you know that the content provider has gone away; at that point the current ContentProviderClient object is invalid, and you should release it. You can acquire a new one if you would like to try to restart the provider and perform new operations on it.

    Parameters
    uri Uri
    Returns
    ContentProviderClient

    addPeriodicSync

    added in API level 8
    void addPeriodicSync (Account account, 
                    String authority, 
                    Bundle extras, 
                    long pollFrequency)

    Specifies that a sync should be requested with the specified the account, authority, and extras at the given frequency. If there is already another periodic sync scheduled with the account, authority and extras then a new periodic sync won't be added, instead the frequency of the previous one will be updated.

    These periodic syncs honor the "syncAutomatically" and "masterSyncAutomatically" settings. Although these sync are scheduled at the specified frequency, it may take longer for it to actually be started if other syncs are ahead of it in the sync operation queue. This means that the actual start time may drift.

    Periodic syncs are not allowed to have any of SYNC_EXTRAS_DO_NOT_RETRY, SYNC_EXTRAS_IGNORE_BACKOFF, SYNC_EXTRAS_IGNORE_SETTINGS, SYNC_EXTRAS_INITIALIZE, SYNC_EXTRAS_FORCE, SYNC_EXTRAS_EXPEDITED, SYNC_EXTRAS_MANUAL set to true. If any are supplied then an IllegalArgumentException will be thrown.

    This method requires the caller to hold the permission WRITE_SYNC_SETTINGS.

    The bundle for a periodic sync can be queried by applications with the correct permissions using getPeriodicSyncs(Account, String), so no sensitive data should be transferred here.

    Parameters
    account Account: the account to specify in the sync
    authority String: the provider to specify in the sync request
    extras Bundle: extra parameters to go along with the sync request
    pollFrequency long: how frequently the sync should be performed, in seconds. A minimum value of 1 hour is enforced.
    Throws
    IllegalArgumentException if an illegal extra was set or if any of the parameters are null.

    addStatusChangeListener

    added in API level 5
    Object addStatusChangeListener (int mask, 
                    SyncStatusObserver callback)

    Request notifications when the different aspects of the SyncManager change. The different items that can be requested are:

    The caller can set one or more of the status types in the mask for any given listener registration.

    Parameters
    mask int: the status change types that will cause the callback to be invoked
    callback SyncStatusObserver: observer to be invoked when the status changes
    Returns
    Object a handle that can be used to remove the listener at a later time

    applyBatch

    added in API level 5
    ContentProviderResult[] applyBatch (String authority, 
                    ArrayList<ContentProviderOperation> operations)

    Applies each of the ContentProviderOperation objects and returns an array of their results. Passes through OperationApplicationException, which may be thrown by the call to apply(ContentProvider, ContentProviderResult[], int). If all the applications succeed then a ContentProviderResult array with the same number of elements as the operations will be returned. It is implementation-specific how many, if any, operations will have been successfully applied if a call to apply results in a OperationApplicationException.

    Parameters
    authority String: the authority of the ContentProvider to which this batch should be applied
    operations ArrayList: the operations to apply
    Returns
    ContentProviderResult[] the results of the applications
    Throws
    OperationApplicationException thrown if an application fails. See apply(ContentProvider, ContentProviderResult[], int) for more information.
    RemoteException thrown if a RemoteException is encountered while attempting to communicate with a remote provider.

    bulkInsert

    added in API level 1
    int bulkInsert (Uri url, 
                    ContentValues[] values)

    Inserts multiple rows into a table at the given URL. This function make no guarantees about the atomicity of the insertions.

    Parameters
    url Uri: The URL of the table to insert into.
    values ContentValues: The initial values for the newly inserted rows. The key is the column name for the field. Passing null will create an empty row.
    Returns
    int the number of newly created rows.

    call

    added in API level 11
    Bundle call (Uri uri, 
                    String method, 
                    String arg, 
                    Bundle extras)

    Call a provider-defined method. This can be used to implement read or write interfaces which are cheaper than using a Cursor and/or do not fit into the traditional table model.

    Parameters
    uri Uri
    method String: provider-defined method name to call. Opaque to framework, but must be non-null.
    arg String: provider-defined String argument. May be null.
    extras Bundle: provider-defined Bundle argument. May be null.
    Returns
    Bundle a result Bundle, possibly null. Will be null if the ContentProvider does not implement call.
    Throws
    NullPointerException if uri or method is null
    IllegalArgumentException if uri is not known

    cancelSync

    added in API level 1
    void cancelSync (Uri uri)

    This method was deprecated in API level 5.
    instead use cancelSync(android.accounts.Account, String)

    Cancel any active or pending syncs that match the Uri. If the uri is null then all syncs will be canceled.

    Parameters
    uri Uri: the uri of the provider to sync or null to sync all providers.

    cancelSync

    added in API level 21
    void cancelSync (SyncRequest request)

    Remove the specified sync. This will cancel any pending or active syncs. If the request is for a periodic sync, this call will remove any future occurrences.

    If a periodic sync is specified, the caller must hold the permission WRITE_SYNC_SETTINGS.

    It is possible to cancel a sync using a SyncRequest object that is not the same object with which you requested the sync. Do so by building a SyncRequest with the same adapter, frequency, and extras bundle.

    Parameters
    request SyncRequest: SyncRequest object containing information about sync to cancel.

    cancelSync

    added in API level 5
    void cancelSync (Account account, 
                    String authority)

    Cancel any active or pending syncs that match account and authority. The account and authority can each independently be set to null, which means that syncs with any account or authority, respectively, will match.

    Parameters
    account Account: filters the syncs that match by this account
    authority String: filters the syncs that match by this authority

    canonicalize

    added in API level 19
    Uri canonicalize (Uri url)

    Transform the given url to a canonical representation of its referenced resource, which can be used across devices, persisted, backed up and restored, etc. The returned Uri is still a fully capable Uri for use with its content provider, allowing you to do all of the same content provider operations as with the original Uri -- query(Uri, String[], Bundle, CancellationSignal), openInputStream(android.net.Uri), etc. The only difference in behavior between the original and new Uris is that the content provider may need to do some additional work at each call using it to resolve it to the correct resource, especially if the canonical Uri has been moved to a different environment.

    If you are moving a canonical Uri between environments, you should perform another call to canonicalize(Uri) with that original Uri to re-canonicalize it for the current environment. Alternatively, you may want to use uncanonicalize(Uri) to transform it to a non-canonical Uri that works only in the current environment but potentially more efficiently than the canonical representation.

    Parameters
    url Uri: The Uri that is to be transformed to a canonical representation. Like all resolver calls, the input can be either a non-canonical or canonical Uri.
    Returns
    Uri Returns the official canonical representation of url, or null if the content provider does not support a canonical representation of the given Uri. Many providers may not support canonicalization of some or all of their Uris.

    delete

    added in API level 1
    int delete (Uri url, 
                    String where, 
                    String[] selectionArgs)

    Deletes row(s) specified by a content URI. If the content provider supports transactions, the deletion will be atomic.

    Parameters
    url Uri: The URL of the row to delete.
    where String: A filter to apply to rows before deleting, formatted as an SQL WHERE clause (excluding the WHERE itself).
    selectionArgs String
    Returns
    int The number of rows deleted.

    getCurrentSync

    added in API level 8
    SyncInfo getCurrentSync ()

    This method was deprecated in API level 11.
    Since multiple concurrent syncs are now supported you should use getCurrentSyncs() to get the accurate list of current syncs. This method returns the first item from the list of current syncs or null if there are none.

    If a sync is active returns the information about it, otherwise returns null.

    This method requires the caller to hold the permission READ_SYNC_STATS.

    Returns
    SyncInfo the SyncInfo for the currently active sync or null if one is not active.

    getCurrentSyncs

    added in API level 11
    List<SyncInfo> getCurrentSyncs ()

    Returns a list with information about all the active syncs. This list will be empty if there are no active syncs.

    This method requires the caller to hold the permission READ_SYNC_STATS.

    Returns
    List<SyncInfo> a List of SyncInfo objects for the currently active syncs.

    getIsSyncable

    added in API level 5
    int getIsSyncable (Account account, 
                    String authority)

    Check if this account/provider is syncable.

    This method requires the caller to hold the permission READ_SYNC_SETTINGS.

    Parameters
    account Account
    authority String
    Returns
    int >0 if it is syncable, 0 if not, and <0 if the state isn't known yet.

    getMasterSyncAutomatically

    added in API level 5
    boolean getMasterSyncAutomatically ()

    Gets the master auto-sync setting that applies to all the providers and accounts. If this is false then the per-provider auto-sync setting is ignored.

    This method requires the caller to hold the permission READ_SYNC_SETTINGS.

    Returns
    boolean the master auto-sync setting that applies to all the providers and accounts

    getOutgoingPersistedUriPermissions

    added in API level 19
    List<UriPermission> getOutgoingPersistedUriPermissions ()

    Return list of all persisted URI permission grants that are hosted by the calling app. That is, the returned permissions have been granted from the calling app. Only grants taken with takePersistableUriPermission(Uri, int) are returned.

    Note: Some of the returned URIs may not be usable until after the user is unlocked.

    Returns
    List<UriPermission>

    getPeriodicSyncs

    added in API level 8
    List<PeriodicSync> getPeriodicSyncs (Account account, 
                    String authority)

    Get the list of information about the periodic syncs for the given account and authority.

    This method requires the caller to hold the permission READ_SYNC_SETTINGS.

    Parameters
    account Account: the account whose periodic syncs we are querying
    authority String: the provider whose periodic syncs we are querying
    Returns
    List<PeriodicSync> a list of PeriodicSync objects. This list may be empty but will never be null.

    getPersistedUriPermissions

    added in API level 19
    List<UriPermission> getPersistedUriPermissions ()

    Return list of all URI permission grants that have been persisted by the calling app. That is, the returned permissions have been granted to the calling app. Only persistable grants taken with takePersistableUriPermission(Uri, int) are returned.

    Note: Some of the returned URIs may not be usable until after the user is unlocked.

    Returns
    List<UriPermission>

    getStreamTypes

    added in API level 11
    String[] getStreamTypes (Uri url, 
                    String mimeTypeFilter)

    Query for the possible MIME types for the representations the given content URL can be returned when opened as as stream with openTypedAssetFileDescriptor(Uri, String, Bundle). Note that the types here are not necessarily a superset of the type returned by getType(Uri) -- many content providers cannot return a raw stream for the structured data that they contain.

    Parameters
    url Uri: A Uri identifying content (either a list or specific type), using the content:// scheme.
    mimeTypeFilter String: The desired MIME type. This may be a pattern, such as */*, to query for all available MIME types that match the pattern.
    Returns
    String[] Returns an array of MIME type strings for all available data streams that match the given mimeTypeFilter. If there are none, null is returned.

    getSyncAdapterTypes

    added in API level 5
    SyncAdapterType[] getSyncAdapterTypes ()

    Get information about the SyncAdapters that are known to the system.

    Returns
    SyncAdapterType[] an array of SyncAdapters that have registered with the system

    getSyncAutomatically

    added in API level 5
    boolean getSyncAutomatically (Account account, 
                    String authority)

    Check if the provider should be synced when a network tickle is received

    This method requires the caller to hold the permission READ_SYNC_SETTINGS.

    Parameters
    account Account: the account whose setting we are querying
    authority String: the provider whose setting we are querying
    Returns
    boolean true if the provider should be synced when a network tickle is received

    getType

    added in API level 1
    String getType (Uri url)

    Return the MIME type of the given content URL.

    Parameters
    url Uri: A Uri identifying content (either a list or specific type), using the content:// scheme.
    Returns
    String A MIME type for the content, or null if the URL is invalid or the type is unknown

    insert

    added in API level 1
    Uri insert (Uri url, 
                    ContentValues values)

    Inserts a row into a table at the given URL. If the content provider supports transactions the insertion will be atomic.

    Parameters
    url Uri: The URL of the table to insert into.
    values ContentValues: The initial values for the newly inserted row. The key is the column name for the field. Passing an empty ContentValues will create an empty row.
    Returns
    Uri the URL of the newly created row.

    isSyncActive

    added in API level 5
    boolean isSyncActive (Account account, 
                    String authority)

    Returns true if there is currently a sync operation for the given account or authority actively being processed.

    This method requires the caller to hold the permission READ_SYNC_STATS.

    Parameters
    account Account: the account whose setting we are querying
    authority String: the provider whose behavior is being queried
    Returns
    boolean true if a sync is active for the given account or authority.

    isSyncPending

    added in API level 5
    boolean isSyncPending (Account account, 
                    String authority)

    Return true if the pending status is true of any matching authorities.

    This method requires the caller to hold the permission READ_SYNC_STATS.

    Parameters
    account Account: the account whose setting we are querying
    authority String: the provider whose behavior is being queried
    Returns
    boolean true if there is a pending sync with the matching account and authority

    notifyChange

    added in API level 1
    void notifyChange (Uri uri, 
                    ContentObserver observer, 
                    boolean syncToNetwork)

    Notify registered observers that a row was updated.

    To observe events sent through this call, use registerContentObserver(Uri, boolean, ContentObserver).

    If syncToNetwork is true, this will attempt to schedule a local sync using the sync adapter that's registered for the authority of the provided uri. No account will be passed to the sync adapter, so all matching accounts will be synchronized.

    Starting in O, all content notifications must be backed by a valid ContentProvider.

    Parameters
    uri Uri: The uri of the content that was changed.
    observer ContentObserver: The observer that originated the change, may be null. The observer that originated the change will only receive the notification if it has requested to receive self-change notifications by implementing deliverSelfNotifications() to return true.
    syncToNetwork boolean: If true, same as NOTIFY_SYNC_TO_NETWORK.

    notifyChange

    added in API level 24
    void notifyChange (Uri uri, 
                    ContentObserver observer, 
                    int flags)

    Notify registered observers that a row was updated.

    To observe events sent through this call, use registerContentObserver(Uri, boolean, ContentObserver).

    If syncToNetwork is true, this will attempt to schedule a local sync using the sync adapter that's registered for the authority of the provided uri. No account will be passed to the sync adapter, so all matching accounts will be synchronized.

    Starting in O, all content notifications must be backed by a valid ContentProvider.

    Parameters
    uri Uri: The uri of the content that was changed.
    observer ContentObserver: The observer that originated the change, may be null. The observer that originated the change will only receive the notification if it has requested to receive self-change notifications by implementing deliverSelfNotifications() to return true.
    flags int: Additional flags: NOTIFY_SYNC_TO_NETWORK.

    notifyChange

    added in API level 1
    void notifyChange (Uri uri, 
                    ContentObserver observer)

    Notify registered observers that a row was updated and attempt to sync changes to the network.

    To observe events sent through this call, use registerContentObserver(Uri, boolean, ContentObserver).

    Starting in O, all content notifications must be backed by a valid ContentProvider.

    Parameters
    uri Uri: The uri of the content that was changed.
    observer ContentObserver: The observer that originated the change, may be null. The observer that originated the change will only receive the notification if it has requested to receive self-change notifications by implementing deliverSelfNotifications() to return true.

    openAssetFileDescriptor

    added in API level 19
    AssetFileDescriptor openAssetFileDescriptor (Uri uri, 
                    String mode, 
                    CancellationSignal cancellationSignal)

    Open a raw file descriptor to access data under a URI. This interacts with the underlying openAssetFile(Uri, String) method of the provider associated with the given URI, to retrieve any file stored there.

    Accepts the following URI schemes:
    The android.resource (SCHEME_ANDROID_RESOURCE) Scheme

    A Uri object can be used to reference a resource in an APK file. The Uri should be one of the following formats:

    • android.resource://package_name/id_number
      package_name is your package name as listed in your AndroidManifest.xml. For example com.example.myapp
      id_number is the int form of the ID.
      The easiest way to construct this form is
      Uri uri = Uri.parse("android.resource://com.example.myapp/" + R.raw.my_resource");
    • android.resource://package_name/type/name
      package_name is your package name as listed in your AndroidManifest.xml. For example com.example.myapp
      type is the string form of the resource type. For example, raw or drawable. name is the string form of the resource name. That is, whatever the file name was in your res directory, without the type extension. The easiest way to construct this form is
      Uri uri = Uri.parse("android.resource://com.example.myapp/raw/my_resource");

    Note that if this function is called for read-only input (mode is "r") on a content: URI, it will instead call openTypedAssetFileDescriptor(Uri, String, Bundle) for you with a MIME type of "*/*". This allows such callers to benefit from any built-in data conversion that a provider implements.

    Parameters
    uri Uri: The desired URI to open.
    mode String: The file mode to use, as per ContentProvider.openAssetFile.
    cancellationSignal CancellationSignal: A signal to cancel the operation in progress, or null if none. If the operation is canceled, then OperationCanceledException will be thrown.
    Returns
    AssetFileDescriptor Returns a new ParcelFileDescriptor pointing to the file. You own this descriptor and are responsible for closing it when done.
    Throws
    FileNotFoundException Throws FileNotFoundException of no file exists under the URI or the mode is invalid.

    openAssetFileDescriptor

    added in API level 3
    AssetFileDescriptor openAssetFileDescriptor (Uri uri, 
                    String mode)

    Open a raw file descriptor to access data under a URI. This interacts with the underlying openAssetFile(Uri, String) method of the provider associated with the given URI, to retrieve any file stored there.

    Accepts the following URI schemes:
    The android.resource (SCHEME_ANDROID_RESOURCE) Scheme

    A Uri object can be used to reference a resource in an APK file. The Uri should be one of the following formats:

    • android.resource://package_name/id_number
      package_name is your package name as listed in your AndroidManifest.xml. For example com.example.myapp
      id_number is the int form of the ID.
      The easiest way to construct this form is
      Uri uri = Uri.parse("android.resource://com.example.myapp/" + R.raw.my_resource");
    • android.resource://package_name/type/name
      package_name is your package name as listed in your AndroidManifest.xml. For example com.example.myapp
      type is the string form of the resource type. For example, raw or drawable. name is the string form of the resource name. That is, whatever the file name was in your res directory, without the type extension. The easiest way to construct this form is
      Uri uri = Uri.parse("android.resource://com.example.myapp/raw/my_resource");

    Note that if this function is called for read-only input (mode is "r") on a content: URI, it will instead call openTypedAssetFileDescriptor(Uri, String, Bundle) for you with a MIME type of "*/*". This allows such callers to benefit from any built-in data conversion that a provider implements.

    Parameters
    uri Uri: The desired URI to open.
    mode String: The file mode to use, as per ContentProvider.openAssetFile.
    Returns
    AssetFileDescriptor Returns a new ParcelFileDescriptor pointing to the file. You own this descriptor and are responsible for closing it when done.
    Throws
    FileNotFoundException Throws FileNotFoundException of no file exists under the URI or the mode is invalid.

    openFileDescriptor

    added in API level 19
    ParcelFileDescriptor openFileDescriptor (Uri uri, 
                    String mode, 
                    CancellationSignal cancellationSignal)

    Open a raw file descriptor to access data under a URI. This is like openAssetFileDescriptor(Uri, String), but uses the underlying openFile(Uri, String) ContentProvider.openFile()} method, so will not work with providers that return sub-sections of files. If at all possible, you should use openAssetFileDescriptor(Uri, String). You will receive a FileNotFoundException exception if the provider returns a sub-section of a file.

    Accepts the following URI schemes:

    See openAssetFileDescriptor(Uri, String) for more information on these schemes.

    If opening with the exclusive "r" or "w" modes, the returned ParcelFileDescriptor could be a pipe or socket pair to enable streaming of data. Opening with the "rw" mode implies a file on disk that supports seeking. If possible, always use an exclusive mode to give the underlying ContentProvider the most flexibility.

    If you are writing a file, and need to communicate an error to the provider, use closeWithError(String).

    Parameters
    uri Uri: The desired URI to open.
    mode String: The file mode to use, as per ContentProvider.openFile.
    cancellationSignal CancellationSignal: A signal to cancel the operation in progress, or null if none. If the operation is canceled, then OperationCanceledException will be thrown.
    Returns
    ParcelFileDescriptor Returns a new ParcelFileDescriptor pointing to the file. You own this descriptor and are responsible for closing it when done.
    Throws
    FileNotFoundException Throws FileNotFoundException if no file exists under the URI or the mode is invalid.

    openFileDescriptor

    added in API level 1
    ParcelFileDescriptor openFileDescriptor (Uri uri, 
                    String mode)

    Open a raw file descriptor to access data under a URI. This is like openAssetFileDescriptor(Uri, String), but uses the underlying openFile(Uri, String) ContentProvider.openFile()} method, so will not work with providers that return sub-sections of files. If at all possible, you should use openAssetFileDescriptor(Uri, String). You will receive a FileNotFoundException exception if the provider returns a sub-section of a file.

    Accepts the following URI schemes:

    See openAssetFileDescriptor(Uri, String) for more information on these schemes.

    If opening with the exclusive "r" or "w" modes, the returned ParcelFileDescriptor could be a pipe or socket pair to enable streaming of data. Opening with the "rw" mode implies a file on disk that supports seeking. If possible, always use an exclusive mode to give the underlying ContentProvider the most flexibility.

    If you are writing a file, and need to communicate an error to the provider, use closeWithError(String).

    Parameters
    uri Uri: The desired URI to open.
    mode String: The file mode to use, as per ContentProvider.openFile.
    Returns
    ParcelFileDescriptor Returns a new ParcelFileDescriptor pointing to the file. You own this descriptor and are responsible for closing it when done.
    Throws
    FileNotFoundException Throws FileNotFoundException if no file exists under the URI or the mode is invalid.

    openInputStream

    added in API level 1
    InputStream openInputStream (Uri uri)

    Open a stream on to the content associated with a content URI. If there is no data associated with the URI, FileNotFoundException is thrown.

    Accepts the following URI schemes:

    See openAssetFileDescriptor(Uri, String) for more information on these schemes.

    Parameters
    uri Uri: The desired URI.
    Returns
    InputStream InputStream
    Throws
    FileNotFoundException if the provided URI could not be opened.

    openOutputStream

    added in API level 1
    OutputStream openOutputStream (Uri uri)

    Synonym for openOutputStream(uri, "w").

    Parameters
    uri Uri
    Returns
    OutputStream
    Throws
    FileNotFoundException if the provided URI could not be opened.

    openOutputStream

    added in API level 3
    OutputStream openOutputStream (Uri uri, 
                    String mode)

    Open a stream on to the content associated with a content URI. If there is no data associated with the URI, FileNotFoundException is thrown.

    Accepts the following URI schemes:

    See openAssetFileDescriptor(Uri, String) for more information on these schemes.

    Parameters
    uri Uri: The desired URI.
    mode String: May be "w", "wa", "rw", or "rwt".
    Returns
    OutputStream OutputStream
    Throws
    FileNotFoundException if the provided URI could not be opened.

    openTypedAssetFileDescriptor

    added in API level 19
    AssetFileDescriptor openTypedAssetFileDescriptor (Uri uri, 
                    String mimeType, 
                    Bundle opts, 
                    CancellationSignal cancellationSignal)

    Open a raw file descriptor to access (potentially type transformed) data from a "content:" URI. This interacts with the underlying openTypedAssetFile(Uri, String, Bundle) method of the provider associated with the given URI, to retrieve retrieve any appropriate data stream for the data stored there.

    Unlike openAssetFileDescriptor(Uri, String), this function only works with "content:" URIs, because content providers are the only facility with an associated MIME type to ensure that the returned data stream is of the desired type.

    All text/* streams are encoded in UTF-8.

    Parameters
    uri Uri: The desired URI to open.
    mimeType String: The desired MIME type of the returned data. This can be a pattern such as */*, which will allow the content provider to select a type, though there is no way for you to determine what type it is returning.
    opts Bundle: Additional provider-dependent options.
    cancellationSignal CancellationSignal: A signal to cancel the operation in progress, or null if none. If the operation is canceled, then OperationCanceledException will be thrown.
    Returns
    AssetFileDescriptor Returns a new ParcelFileDescriptor from which you can read the data stream from the provider. Note that this may be a pipe, meaning you can't seek in it. The only seek you should do is if the AssetFileDescriptor contains an offset, to move to that offset before reading. You own this descriptor and are responsible for closing it when done.
    Throws
    FileNotFoundException Throws FileNotFoundException of no data of the desired type exists under the URI.

    openTypedAssetFileDescriptor

    added in API level 11
    AssetFileDescriptor openTypedAssetFileDescriptor (Uri uri, 
                    String mimeType, 
                    Bundle opts)

    Open a raw file descriptor to access (potentially type transformed) data from a "content:" URI. This interacts with the underlying openTypedAssetFile(Uri, String, Bundle) method of the provider associated with the given URI, to retrieve retrieve any appropriate data stream for the data stored there.

    Unlike openAssetFileDescriptor(Uri, String), this function only works with "content:" URIs, because content providers are the only facility with an associated MIME type to ensure that the returned data stream is of the desired type.

    All text/* streams are encoded in UTF-8.

    Parameters
    uri Uri: The desired URI to open.
    mimeType String: The desired MIME type of the returned data. This can be a pattern such as */*, which will allow the content provider to select a type, though there is no way for you to determine what type it is returning.
    opts Bundle: Additional provider-dependent options.
    Returns
    AssetFileDescriptor Returns a new ParcelFileDescriptor from which you can read the data stream from the provider. Note that this may be a pipe, meaning you can't seek in it. The only seek you should do is if the AssetFileDescriptor contains an offset, to move to that offset before reading. You own this descriptor and are responsible for closing it when done.
    Throws
    FileNotFoundException Throws FileNotFoundException of no data of the desired type exists under the URI.

    query

    Cursor query (Uri uri, 
                    String[] projection, 
                    Bundle queryArgs, 
                    CancellationSignal cancellationSignal)

    Query the given URI, returning a Cursor over the result set with support for cancellation.

    For best performance, the caller should follow these guidelines:

  • Provide an explicit projection, to prevent reading data from storage that aren't going to be used. Provider must identify which QUERY_ARG_SORT* arguments were honored during the preparation of the result set by including the respective argument keys in the Cursor extras Bundle. See EXTRA_HONORED_ARGS for details.

    Parameters
    uri Uri: The URI, using the content:// scheme, for the content to retrieve.
    projection String: A list of which columns to return. Passing null will return all columns, which is inefficient.
    queryArgs Bundle: A Bundle containing any arguments to the query.
    cancellationSignal CancellationSignal: A signal to cancel the operation in progress, or null if none. If the operation is canceled, then OperationCanceledException will be thrown when the query is executed.
    Returns
    Cursor A Cursor object, which is positioned before the first entry, or null
  • query

    added in API level 16
    Cursor query (Uri uri, 
                    String[] projection, 
                    String selection, 
                    String[] selectionArgs, 
                    String sortOrder, 
                    CancellationSignal cancellationSignal)

    Query the given URI, returning a Cursor over the result set with optional support for cancellation.

    For best performance, the caller should follow these guidelines:

    • Provide an explicit projection, to prevent reading data from storage that aren't going to be used.
    • Use question mark parameter markers such as 'phone=?' instead of explicit values in the selection parameter, so that queries that differ only by those values will be recognized as the same for caching purposes.

    Parameters
    uri Uri: The URI, using the content:// scheme, for the content to retrieve.
    projection String: A list of which columns to return. Passing null will return all columns, which is inefficient.
    selection String: A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given URI.
    selectionArgs String: You may include ?s in selection, which will be replaced by the values from selectionArgs, in the order that they appear in the selection. The values will be bound as Strings.
    sortOrder String: How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
    cancellationSignal CancellationSignal: A signal to cancel the operation in progress, or null if none. If the operation is canceled, then OperationCanceledException will be thrown when the query is executed.
    Returns
    Cursor A Cursor object, which is positioned before the first entry, or null

    See also:

    query

    added in API level 1
    Cursor query (Uri uri, 
                    String[] projection, 
                    String selection, 
                    String[] selectionArgs, 
                    String sortOrder)

    Query the given URI, returning a Cursor over the result set.

    For best performance, the caller should follow these guidelines:

    • Provide an explicit projection, to prevent reading data from storage that aren't going to be used.
    • Use question mark parameter markers such as 'phone=?' instead of explicit values in the selection parameter, so that queries that differ only by those values will be recognized as the same for caching purposes.

    Parameters
    uri Uri: The URI, using the content:// scheme, for the content to retrieve.
    projection String: A list of which columns to return. Passing null will return all columns, which is inefficient.
    selection String: A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given URI.
    selectionArgs String: You may include ?s in selection, which will be replaced by the values from selectionArgs, in the order that they appear in the selection. The values will be bound as Strings.
    sortOrder String: How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
    Returns
    Cursor A Cursor object, which is positioned before the first entry, or null

    See also:

    refresh

    boolean refresh (Uri url, 
                    Bundle args, 
                    CancellationSignal cancellationSignal)

    This allows clients to request an explicit refresh of content identified by uri.

    Client code should only invoke this method when there is a strong indication (such as a user initiated pull to refresh gesture) that the content is stale.

    Parameters
    url Uri: The Uri identifying the data to refresh.
    args Bundle: Additional options from the client. The definitions of these are specific to the content provider being called.
    cancellationSignal CancellationSignal: A signal to cancel the operation in progress, or null if none. For example, if you called refresh on a particular uri, you should call throwIfCanceled() to check whether the client has canceled the refresh request.
    Returns
    boolean true if the provider actually tried refreshing.

    registerContentObserver

    added in API level 1
    void registerContentObserver (Uri uri, 
                    boolean notifyForDescendants, 
                    ContentObserver observer)

    Register an observer class that gets callbacks when data identified by a given content URI changes.

    Starting in O, all content notifications must be backed by a valid ContentProvider.

    Parameters
    uri Uri: The URI to watch for changes. This can be a specific row URI, or a base URI for a whole class of content.
    notifyForDescendants boolean: When false, the observer will be notified whenever a change occurs to the exact URI specified by uri or to one of the URI's ancestors in the path hierarchy. When true, the observer will also be notified whenever a change occurs to the URI's descendants in the path hierarchy.
    observer ContentObserver: The object that receives callbacks when changes occur.

    releasePersistableUriPermission

    added in API level 19
    void releasePersistableUriPermission (Uri uri, 
                    int modeFlags)

    Relinquish a persisted URI permission grant. The URI must have been previously made persistent with takePersistableUriPermission(Uri, int). Any non-persistent grants to the calling package will remain intact.

    Parameters
    uri Uri
    modeFlags int

    removePeriodicSync

    added in API level 8
    void removePeriodicSync (Account account, 
                    String authority, 
                    Bundle extras)

    Remove a periodic sync. Has no affect if account, authority and extras don't match an existing periodic sync.

    This method requires the caller to hold the permission WRITE_SYNC_SETTINGS.

    Parameters
    account Account: the account of the periodic sync to remove
    authority String: the provider of the periodic sync to remove
    extras Bundle: the extras of the periodic sync to remove

    removeStatusChangeListener

    added in API level 5
    void removeStatusChangeListener (Object handle)

    Remove a previously registered status change listener.

    Parameters
    handle Object: the handle that was returned by addStatusChangeListener(int, SyncStatusObserver)

    requestSync

    added in API level 5
    void requestSync (Account account, 
                    String authority, 
                    Bundle extras)

    Start an asynchronous sync operation. If you want to monitor the progress of the sync you may register a SyncObserver. Only values of the following types may be used in the extras bundle:

    • Integer
    • Long
    • Boolean
    • Float
    • Double
    • String
    • Account
    • null

    Parameters
    account Account: which account should be synced
    authority String: which authority should be synced
    extras Bundle: any extras to pass to the SyncAdapter.

    requestSync

    added in API level 19
    void requestSync (SyncRequest request)

    Register a sync with the SyncManager. These requests are built using the SyncRequest.Builder.

    Parameters
    request SyncRequest

    setIsSyncable

    added in API level 5
    void setIsSyncable (Account account, 
                    String authority, 
                    int syncable)

    Set whether this account/provider is syncable.

    This method requires the caller to hold the permission WRITE_SYNC_SETTINGS.

    Parameters
    account Account
    authority String
    syncable int: >0 denotes syncable, 0 means not syncable, <0 means unknown

    setMasterSyncAutomatically

    added in API level 5
    void setMasterSyncAutomatically (boolean sync)

    Sets the master auto-sync setting that applies to all the providers and accounts. If this is false then the per-provider auto-sync setting is ignored.

    This method requires the caller to hold the permission WRITE_SYNC_SETTINGS.

    Parameters
    sync boolean: the master auto-sync setting that applies to all the providers and accounts

    setSyncAutomatically

    added in API level 5
    void setSyncAutomatically (Account account, 
                    String authority, 
                    boolean sync)

    Set whether or not the provider is synced when it receives a network tickle.

    This method requires the caller to hold the permission WRITE_SYNC_SETTINGS.

    Parameters
    account Account: the account whose setting we are querying
    authority String: the provider whose behavior is being controlled
    sync boolean: true if the provider should be synced when tickles are received for it

    startSync

    added in API level 1
    void startSync (Uri uri, 
                    Bundle extras)

    This method was deprecated in API level 5.
    instead use requestSync(android.accounts.Account, String, android.os.Bundle)

    Start an asynchronous sync operation. If you want to monitor the progress of the sync you may register a SyncObserver. Only values of the following types may be used in the extras bundle:

    • Integer
    • Long
    • Boolean
    • Float
    • Double
    • String
    • Account
    • null

    Parameters
    uri Uri: the uri of the provider to sync or null to sync all providers.
    extras Bundle: any extras to pass to the SyncAdapter.

    takePersistableUriPermission

    added in API level 19
    void takePersistableUriPermission (Uri uri, 
                    int modeFlags)

    Take a persistable URI permission grant that has been offered. Once taken, the permission grant will be remembered across device reboots. Only URI permissions granted with FLAG_GRANT_PERSISTABLE_URI_PERMISSION can be persisted. If the grant has already been persisted, taking it again will touch getPersistedTime().

    Parameters
    uri Uri
    modeFlags int

    uncanonicalize

    added in API level 19
    Uri uncanonicalize (Uri url)

    Given a canonical Uri previously generated by canonicalize(Uri), convert it to its local non-canonical form. This can be useful in some cases where you know that you will only be using the Uri in the current environment and want to avoid any possible overhead when using it with the content provider or want to verify that the referenced data exists at all in the new environment.

    Parameters
    url Uri: The canonical Uri that is to be convered back to its non-canonical form.
    Returns
    Uri Returns the non-canonical representation of url. This will return null if data identified by the canonical Uri can not be found in the current environment; callers must always check for null and deal with that by appropriately falling back to an alternative.

    See also:

    unregisterContentObserver

    added in API level 1
    void unregisterContentObserver (ContentObserver observer)

    Unregisters a change observer.

    Parameters
    observer ContentObserver: The previously registered observer that is no longer needed.

    update

    added in API level 1
    int update (Uri uri, 
                    ContentValues values, 
                    String where, 
                    String[] selectionArgs)

    Update row(s) in a content URI. If the content provider supports transactions the update will be atomic.

    Parameters
    uri Uri: The URI to modify.
    values ContentValues: The new field values. The key is the column name for the field. A null value will remove an existing field value.
    where String: A filter to apply to rows before updating, formatted as an SQL WHERE clause (excluding the WHERE itself).
    selectionArgs String
    Returns
    int the number of rows updated.
    Throws
    NullPointerException if uri or values are null

    validateSyncExtrasBundle

    added in API level 1
    void validateSyncExtrasBundle (Bundle extras)

    Check that only values of the following types are in the Bundle:

    • Integer
    • Long
    • Boolean
    • Float
    • Double
    • String
    • Account
    • null

    Parameters
    extras Bundle: the Bundle to check
    This site uses cookies to store your preferences for site-specific language and display options.

    This class requires API level or higher

    This doc is hidden because your selected API level for the documentation is . You can change the documentation API level with the selector above the left navigation.

    For more information about specifying the API level your app requires, read Supporting Different Platform Versions.

    Take a one-minute survey?
    Help us improve Android tools and documentation.