Skip to content

Most visited

Recently visited

navigation

DocumentsProvider

public abstract class DocumentsProvider
extends ContentProvider

java.lang.Object
   ↳ android.content.ContentProvider
     ↳ android.provider.DocumentsProvider


Base class for a document provider. A document provider offers read and write access to durable files, such as files stored on a local disk, or files in a cloud storage service. To create a document provider, extend this class, implement the abstract methods, and add it to your manifest like this:

<manifest>
    ...
    <application>
        ...
        <provider
            android:name="com.example.MyCloudProvider"
            android:authorities="com.example.mycloudprovider"
            android:exported="true"
            android:grantUriPermissions="true"
            android:permission="android.permission.MANAGE_DOCUMENTS"
            android:enabled="@bool/isAtLeastKitKat">
            <intent-filter>
                <action android:name="android.content.action.DOCUMENTS_PROVIDER" />
            </intent-filter>
        </provider>
        ...
    </application>
</manifest>

When defining your provider, you must protect it with MANAGE_DOCUMENTS, which is a permission only the system can obtain. Applications cannot use a documents provider directly; they must go through ACTION_OPEN_DOCUMENT or ACTION_CREATE_DOCUMENT which requires a user to actively navigate and select documents. When a user selects documents through that UI, the system issues narrow URI permission grants to the requesting application.

Documents

A document can be either an openable stream (with a specific MIME type), or a directory containing additional documents (with the MIME_TYPE_DIR MIME type). Each directory represents the top of a subtree containing zero or more documents, which can recursively contain even more documents and directories.

Each document can have different capabilities, as described by COLUMN_FLAGS. For example, if a document can be represented as a thumbnail, your provider can set FLAG_SUPPORTS_THUMBNAIL and implement openDocumentThumbnail(String, Point, CancellationSignal) to return that thumbnail.

Each document under a provider is uniquely referenced by its COLUMN_DOCUMENT_ID, which must not change once returned. A single document can be included in multiple directories when responding to queryChildDocuments(String, String[], String). For example, a provider might surface a single photo in multiple locations: once in a directory of geographic locations, and again in a directory of dates.

Roots

All documents are surfaced through one or more "roots." Each root represents the top of a document tree that a user can navigate. For example, a root could represent an account or a physical storage device. Similar to documents, each root can have capabilities expressed through COLUMN_FLAGS.

See also:

Summary

Inherited constants

From interface android.content.ComponentCallbacks2

Public constructors

DocumentsProvider()

Public methods

void attachInfo(Context context, ProviderInfo info)

Implementation is provided by the parent class.

Bundle call(String method, String arg, Bundle extras)

Implementation is provided by the parent class.

Uri canonicalize(Uri uri)

Implementation is provided by the parent class.

String copyDocument(String sourceDocumentId, String targetParentDocumentId)

Copy the requested document or a document tree.

String createDocument(String parentDocumentId, String mimeType, String displayName)

Create a new document and return its newly generated COLUMN_DOCUMENT_ID.

IntentSender createWebLinkIntent(String documentId, Bundle options)

Creates an intent sender for a web link, if the document is web linkable.

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

Implementation is provided by the parent class.

void deleteDocument(String documentId)

Delete the requested document.

void ejectRoot(String rootId)

Ejects the root.

DocumentsContract.Path findDocumentPath(String parentDocumentId, String childDocumentId)

Finds the canonical path for the requested document.

String[] getDocumentStreamTypes(String documentId, String mimeTypeFilter)

Return a list of streamable MIME types matching the filter, which can be passed to openTypedDocument(String, String, Bundle, CancellationSignal).

String getDocumentType(String documentId)

Return concrete MIME type of the requested document.

String[] getStreamTypes(Uri uri, String mimeTypeFilter)

Called by a client to determine the types of data streams that this content provider support for the given URI.

final String getType(Uri uri)

Implementation is provided by the parent class.

final Uri insert(Uri uri, ContentValues values)

Implementation is provided by the parent class.

boolean isChildDocument(String parentDocumentId, String documentId)

Test if a document is descendant (child, grandchild, etc) from the given parent.

String moveDocument(String sourceDocumentId, String sourceParentDocumentId, String targetParentDocumentId)

Move the requested document or a document tree.

final AssetFileDescriptor openAssetFile(Uri uri, String mode, CancellationSignal signal)

Implementation is provided by the parent class.

final AssetFileDescriptor openAssetFile(Uri uri, String mode)

Implementation is provided by the parent class.

abstract ParcelFileDescriptor openDocument(String documentId, String mode, CancellationSignal signal)

Open and return the requested document.

AssetFileDescriptor openDocumentThumbnail(String documentId, Point sizeHint, CancellationSignal signal)

Open and return a thumbnail of the requested document.

final ParcelFileDescriptor openFile(Uri uri, String mode, CancellationSignal signal)

Implementation is provided by the parent class.

final ParcelFileDescriptor openFile(Uri uri, String mode)

Implementation is provided by the parent class.

final AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts)

Implementation is provided by the parent class.

final AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, Bundle opts, CancellationSignal signal)

Implementation is provided by the parent class.

AssetFileDescriptor openTypedDocument(String documentId, String mimeTypeFilter, Bundle opts, CancellationSignal signal)

Open and return the document in a format matching the specified MIME type filter.

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

Implementation is provided by the parent class.

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

WARNING: Sub-classes should not override this method.

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

Implement this to handle query requests from clients.

Cursor queryChildDocuments(String parentDocumentId, String[] projection, Bundle queryArgs)

Override this method to return the children documents contained in the requested directory.

abstract Cursor queryChildDocuments(String parentDocumentId, String[] projection, String sortOrder)

Return the children documents contained in the requested directory.

abstract Cursor queryDocument(String documentId, String[] projection)

Return metadata for the single requested document.

Cursor queryRecentDocuments(String rootId, String[] projection)

Return recently modified documents under the requested root.

abstract Cursor queryRoots(String[] projection)

Return all roots currently provided.

Cursor querySearchDocuments(String rootId, String query, String[] projection)

Return documents that match the given query under the requested root.

void removeDocument(String documentId, String parentDocumentId)

Removes the requested document or a document tree.

String renameDocument(String documentId, String displayName)

Rename an existing document.

final void revokeDocumentPermission(String documentId)

Revoke any active permission grants for the given COLUMN_DOCUMENT_ID, usually called when a document becomes invalid.

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

Implementation is provided by the parent class.

Inherited methods

From class android.content.ContentProvider
From class java.lang.Object
From interface android.content.ComponentCallbacks2
From interface android.content.ComponentCallbacks

Public constructors

DocumentsProvider

added in API level 19
DocumentsProvider ()

Public methods

attachInfo

added in API level 19
void attachInfo (Context context, 
                ProviderInfo info)

Implementation is provided by the parent class.

Parameters
context Context: The context this provider is running in

info ProviderInfo: Registered information about this content provider

call

added in API level 19
Bundle call (String method, 
                String arg, 
                Bundle extras)

Implementation is provided by the parent class. Can be overridden to provide additional functionality, but subclasses must always call the superclass. If the superclass returns null, the subclass may implement custom behavior.

If you override this method you must call through to the superclass implementation.

Parameters
method String: method name to call. Opaque to framework, but should not be null.

arg String: provider-defined String argument. May be null.

extras Bundle: provider-defined Bundle argument. May be null.

Returns
Bundle provider-defined return value. May be null, which is also the default for providers which don't implement any call methods.

canonicalize

added in API level 19
Uri canonicalize (Uri uri)

Implementation is provided by the parent class. Can be overridden to provide additional functionality, but subclasses must always call the superclass. If the superclass returns null, the subclass may implement custom behavior.

This is typically used to resolve a subtree URI into a concrete document reference, issuing a narrower single-document URI permission grant along the way.

If you override this method you must call through to the superclass implementation.

Parameters
uri Uri: The Uri to canonicalize.

Returns
Uri Return the canonical representation of url, or null if canonicalization of that Uri is not supported.

See also:

copyDocument

added in API level 24
String copyDocument (String sourceDocumentId, 
                String targetParentDocumentId)

Copy the requested document or a document tree.

Copies a document including all child documents to another location within the same document provider. Upon completion returns the document id of the copied document at the target destination. null must never be returned.

Parameters
sourceDocumentId String: the document to copy.

targetParentDocumentId String: the target document to be copied into as a child.

Returns
String

Throws
AuthenticationRequiredException If authentication is required from the user (such as login credentials), but it is not guaranteed that the client will handle this properly.
FileNotFoundException

createDocument

added in API level 19
String createDocument (String parentDocumentId, 
                String mimeType, 
                String displayName)

Create a new document and return its newly generated COLUMN_DOCUMENT_ID. You must allocate a new COLUMN_DOCUMENT_ID to represent the document, which must not change once returned.

Parameters
parentDocumentId String: the parent directory to create the new document under.

mimeType String: the concrete MIME type associated with the new document. If the MIME type is not supported, the provider must throw.

displayName String: the display name of the new document. The provider may alter this name to meet any internal constraints, such as avoiding conflicting names.

Returns
String

Throws
AuthenticationRequiredException If authentication is required from the user (such as login credentials), but it is not guaranteed that the client will handle this properly.
FileNotFoundException

createWebLinkIntent

added in API level 26
IntentSender createWebLinkIntent (String documentId, 
                Bundle options)

Creates an intent sender for a web link, if the document is web linkable.

AuthenticationRequiredException can be thrown if user does not have sufficient permission for the linked document. Before any new permissions are granted for the linked document, a visible UI must be shown, so the user can explicitly confirm whether the permission grants are expected. The user must be able to cancel the operation.

Options passed as an argument may include a list of recipients, such as email addresses. The provider should reflect these options if possible, but it's acceptable to ignore them. In either case, confirmation UI must be shown before any new permission grants are granted.

It is all right to generate a web link without granting new permissions, if opening the link would result in a page for requesting permission access. If it's impossible then the operation must fail by throwing an exception.

Parameters
documentId String: the document to create a web link intent for.

options Bundle: additional information, such as list of recipients. Optional.

This value may be null.

Returns
IntentSender

Throws
AuthenticationRequiredException If authentication is required from the user (such as login credentials), but it is not guaranteed that the client will handle this properly.
FileNotFoundException

See also:

delete

added in API level 19
int delete (Uri uri, 
                String selection, 
                String[] selectionArgs)

Implementation is provided by the parent class. Throws by default, and cannot be overriden.

Parameters
uri Uri: The full URI to query, including a row ID (if a specific record is requested).

selection String: An optional restriction to apply to rows when deleting.

selectionArgs String

Returns
int The number of rows affected.

See also:

deleteDocument

added in API level 19
void deleteDocument (String documentId)

Delete the requested document.

Upon returning, any URI permission grants for the given document will be revoked. If additional documents were deleted as a side effect of this call (such as documents inside a directory) the implementor is responsible for revoking those permissions using revokeDocumentPermission(String).

Parameters
documentId String: the document to delete.

Throws
AuthenticationRequiredException If authentication is required from the user (such as login credentials), but it is not guaranteed that the client will handle this properly.
FileNotFoundException

ejectRoot

added in API level 26
void ejectRoot (String rootId)

Ejects the root. Throws IllegalStateException if ejection failed.

Parameters
rootId String: the root to be ejected.

See also:

findDocumentPath

added in API level 26
DocumentsContract.Path findDocumentPath (String parentDocumentId, 
                String childDocumentId)

Finds the canonical path for the requested document. The path must start from the parent document if parentDocumentId is not null or the root document if parentDocumentId is null. If there are more than one path to this document, return the most typical one. Include both the parent document or root document and the requested document in the returned path.

This API assumes that document ID has enough info to infer the root. Different roots should use different document ID to refer to the same document.

Parameters
parentDocumentId String: the document from which the path starts if not null, or null to indicate a path from the root is requested.

childDocumentId String: the document which path is requested.

Returns
DocumentsContract.Path the path of the requested document. If parentDocumentId is null returned root ID must not be null. If parentDocumentId is not null returned root ID must be null.

Throws
AuthenticationRequiredException If authentication is required from the user (such as login credentials), but it is not guaranteed that the client will handle this properly.
FileNotFoundException

getDocumentStreamTypes

added in API level 24
String[] getDocumentStreamTypes (String documentId, 
                String mimeTypeFilter)

Return a list of streamable MIME types matching the filter, which can be passed to openTypedDocument(String, String, Bundle, CancellationSignal).

The default implementation returns a MIME type provided by queryDocument(String, String[]) as long as it matches the filter and the document does not have the FLAG_VIRTUAL_DOCUMENT flag set.

Virtual documents must have at least one streamable format.

Parameters
documentId String

mimeTypeFilter String

Returns
String[]

See also:

getDocumentType

added in API level 19
String getDocumentType (String documentId)

Return concrete MIME type of the requested document. Must match the value of COLUMN_MIME_TYPE for this document. The default implementation queries queryDocument(String, String[]), so providers may choose to override this as an optimization.

Parameters
documentId String

Returns
String

Throws
AuthenticationRequiredException If authentication is required from the user (such as login credentials), but it is not guaranteed that the client will handle this properly.
FileNotFoundException

getStreamTypes

added in API level 19
String[] getStreamTypes (Uri uri, 
                String mimeTypeFilter)

Called by a client to determine the types of data streams that this content provider support for the given URI.

Overriding this method is deprecated. Override openTypedDocument(String, String, Bundle, CancellationSignal) instead.

Parameters
uri Uri: The data in the content provider being queried.

mimeTypeFilter String: The type of data the client desires. May be a pattern, such as */* to retrieve all possible data types.

Returns
String[] Returns null if there are no possible data streams for the given mimeTypeFilter. Otherwise returns an array of all available concrete MIME types.

See also:

getType

added in API level 19
String getType (Uri uri)

Implementation is provided by the parent class. Cannot be overriden.

Parameters
uri Uri: the URI to query.

Returns
String a MIME type string, or null if there is no type.

See also:

insert

added in API level 19
Uri insert (Uri uri, 
                ContentValues values)

Implementation is provided by the parent class. Throws by default, and cannot be overriden.

Parameters
uri Uri: The content:// URI of the insertion request. This must not be null.

values ContentValues: A set of column_name/value pairs to add to the database. This must not be null.

Returns
Uri The URI for the newly inserted item.

See also:

isChildDocument

added in API level 21
boolean isChildDocument (String parentDocumentId, 
                String documentId)

Test if a document is descendant (child, grandchild, etc) from the given parent. For example, providers must implement this to support ACTION_OPEN_DOCUMENT_TREE. You should avoid making network requests to keep this request fast.

Parameters
parentDocumentId String: parent to verify against.

documentId String: child to verify.

Returns
boolean if given document is a descendant of the given parent.

See also:

moveDocument

added in API level 24
String moveDocument (String sourceDocumentId, 
                String sourceParentDocumentId, 
                String targetParentDocumentId)

Move the requested document or a document tree.

Moves a document including all child documents to another location within the same document provider. Upon completion returns the document id of the copied document at the target destination. null must never be returned.

It's the responsibility of the provider to revoke grants if the document is no longer accessible using sourceDocumentId.

Parameters
sourceDocumentId String: the document to move.

sourceParentDocumentId String: the parent of the document to move.

targetParentDocumentId String: the target document to be a new parent of the source document.

Returns
String

Throws
AuthenticationRequiredException If authentication is required from the user (such as login credentials), but it is not guaranteed that the client will handle this properly.
FileNotFoundException

openAssetFile

added in API level 19
AssetFileDescriptor openAssetFile (Uri uri, 
                String mode, 
                CancellationSignal signal)

Implementation is provided by the parent class. Cannot be overriden.

Parameters
uri Uri: The URI whose file is to be opened.

mode String: Access mode for the file. May be "r" for read-only access, "w" for write-only access (erasing whatever data is currently in the file), "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data, and "rwt" for read and write access that truncates any existing file.

signal CancellationSignal: A signal to cancel the operation in progress, or null if none. For example, if you are downloading a file from the network to service a "rw" mode request, you should periodically call throwIfCanceled() to check whether the client has canceled the request and abort the download.

Returns
AssetFileDescriptor Returns a new AssetFileDescriptor which you can use to access the file.

Throws
FileNotFoundException

See also:

openAssetFile

added in API level 19
AssetFileDescriptor openAssetFile (Uri uri, 
                String mode)

Implementation is provided by the parent class. Cannot be overriden.

Parameters
uri Uri: The URI whose file is to be opened.

mode String: Access mode for the file. May be "r" for read-only access, "w" for write-only access (erasing whatever data is currently in the file), "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data, and "rwt" for read and write access that truncates any existing file.

Returns
AssetFileDescriptor Returns a new AssetFileDescriptor which you can use to access the file.

Throws
FileNotFoundException

See also:

openDocument

added in API level 19
ParcelFileDescriptor openDocument (String documentId, 
                String mode, 
                CancellationSignal signal)

Open and return the requested document.

Your provider should return a reliable ParcelFileDescriptor to detect when the remote caller has finished reading or writing the document.

Mode "r" should always be supported. Provider should throw UnsupportedOperationException if the passing mode is not supported. You may return a pipe or socket pair if the mode is exclusively "r" or "w", but complex modes like "rw" imply a normal file on disk that supports seeking.

If you block while downloading content, you should periodically check isCanceled() to abort abandoned open requests.

Parameters
documentId String: the document to return.

mode String: the mode to open with, such as 'r', 'w', or 'rw'.

signal CancellationSignal: used by the caller to signal if the request should be cancelled. May be null.

Returns
ParcelFileDescriptor

Throws
AuthenticationRequiredException If authentication is required from the user (such as login credentials), but it is not guaranteed that the client will handle this properly.
FileNotFoundException

See also:

openDocumentThumbnail

added in API level 19
AssetFileDescriptor openDocumentThumbnail (String documentId, 
                Point sizeHint, 
                CancellationSignal signal)

Open and return a thumbnail of the requested document.

A provider should return a thumbnail closely matching the hinted size, attempting to serve from a local cache if possible. A provider should never return images more than double the hinted size.

If you perform expensive operations to download or generate a thumbnail, you should periodically check isCanceled() to abort abandoned thumbnail requests.

Parameters
documentId String: the document to return.

sizeHint Point: hint of the optimal thumbnail dimensions.

signal CancellationSignal: used by the caller to signal if the request should be cancelled. May be null.

Returns
AssetFileDescriptor

Throws
AuthenticationRequiredException If authentication is required from the user (such as login credentials), but it is not guaranteed that the client will handle this properly.
FileNotFoundException

See also:

openFile

added in API level 19
ParcelFileDescriptor openFile (Uri uri, 
                String mode, 
                CancellationSignal signal)

Implementation is provided by the parent class. Cannot be overriden.

Parameters
uri Uri: The URI whose file is to be opened.

mode String: Access mode for the file. May be "r" for read-only access, "w" for write-only access, "rw" for read and write access, or "rwt" for read and write access that truncates any existing file.

signal CancellationSignal: A signal to cancel the operation in progress, or null if none. For example, if you are downloading a file from the network to service a "rw" mode request, you should periodically call throwIfCanceled() to check whether the client has canceled the request and abort the download.

Returns
ParcelFileDescriptor Returns a new ParcelFileDescriptor which you can use to access the file.

Throws
FileNotFoundException

See also:

openFile

added in API level 19
ParcelFileDescriptor openFile (Uri uri, 
                String mode)

Implementation is provided by the parent class. Cannot be overriden.

Parameters
uri Uri: The URI whose file is to be opened.

mode String: Access mode for the file. May be "r" for read-only access, "rw" for read and write access, or "rwt" for read and write access that truncates any existing file.

Returns
ParcelFileDescriptor Returns a new ParcelFileDescriptor which you can use to access the file.

Throws
FileNotFoundException

See also:

openTypedAssetFile

added in API level 19
AssetFileDescriptor openTypedAssetFile (Uri uri, 
                String mimeTypeFilter, 
                Bundle opts)

Implementation is provided by the parent class. Cannot be overriden.

Parameters
uri Uri: The data in the content provider being queried.

mimeTypeFilter String: The type of data the client desires. May be a pattern, such as */*, if the caller does not have specific type requirements; in this case the content provider will pick its best type matching the pattern.

opts Bundle: Additional options from the client. The definitions of these are specific to the content provider being called.

Returns
AssetFileDescriptor Returns a new AssetFileDescriptor from which the client can read data of the desired type.

Throws
FileNotFoundException

See also:

openTypedAssetFile

added in API level 19
AssetFileDescriptor openTypedAssetFile (Uri uri, 
                String mimeTypeFilter, 
                Bundle opts, 
                CancellationSignal signal)

Implementation is provided by the parent class. Cannot be overriden.

Parameters
uri Uri: The data in the content provider being queried.

mimeTypeFilter String: The type of data the client desires. May be a pattern, such as */*, if the caller does not have specific type requirements; in this case the content provider will pick its best type matching the pattern.

opts Bundle: Additional options from the client. The definitions of these are specific to the content provider being called.

signal CancellationSignal: A signal to cancel the operation in progress, or null if none. For example, if you are downloading a file from the network to service a "rw" mode request, you should periodically call throwIfCanceled() to check whether the client has canceled the request and abort the download.

Returns
AssetFileDescriptor Returns a new AssetFileDescriptor from which the client can read data of the desired type.

Throws
FileNotFoundException

See also:

openTypedDocument

added in API level 24
AssetFileDescriptor openTypedDocument (String documentId, 
                String mimeTypeFilter, 
                Bundle opts, 
                CancellationSignal signal)

Open and return the document in a format matching the specified MIME type filter.

A provider may perform a conversion if the documents's MIME type is not matching the specified MIME type filter.

Virtual documents must have at least one streamable format.

Parameters
documentId String: the document to return.

mimeTypeFilter String: the MIME type filter for the requested format. May be *\/*, which matches any MIME type.

opts Bundle: extra options from the client. Specific to the content provider.

signal CancellationSignal: used by the caller to signal if the request should be cancelled. May be null.

Returns
AssetFileDescriptor

Throws
AuthenticationRequiredException If authentication is required from the user (such as login credentials), but it is not guaranteed that the client will handle this properly.
FileNotFoundException

See also:

query

added in API level 26
Cursor query (Uri uri, 
                String[] projection, 
                Bundle queryArgs, 
                CancellationSignal cancellationSignal)

Implementation is provided by the parent class. Cannot be overriden.

Parameters
uri Uri: The URI to query. This will be the full URI sent by the client.

projection String: The list of columns to put into the cursor. If null provide a default set of columns.

queryArgs Bundle: A Bundle containing all additional information necessary for the query. Values in the Bundle may include SQL style arguments.

cancellationSignal CancellationSignal: A signal to cancel the operation in progress, or null.

Returns
Cursor a Cursor or null.

See also:

query

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

WARNING: Sub-classes should not override this method. This method is non-final solely for the purposes of backwards compatibility.

Parameters
uri Uri: 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 String: The list of columns to put into the cursor. If null all columns are included.

selection String: A selection criteria to apply when filtering rows. If null then all rows are included.

selectionArgs String: You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.

sortOrder String: How the rows in the cursor should be sorted. If null then the provider is free to define the sort order.

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 or null.

See also:

query

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

Implement this to handle query requests from clients.

Apps targeting O or higher should override query(Uri, String[], Bundle, CancellationSignal) and provide a stub implementation of this method.

This method can be called from multiple threads, as described in Processes and Threads.

Example client call:

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

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

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

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

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

Parameters
uri Uri: 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 String: The list of columns to put into the cursor. If null all columns are included.

selection String: A selection criteria to apply when filtering rows. If null then all rows are included.

selectionArgs String: You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.

sortOrder String: How the rows in the cursor should be sorted. If null then the provider is free to define the sort order.

Returns
Cursor a Cursor or null.

queryChildDocuments

added in API level 26
Cursor queryChildDocuments (String parentDocumentId, 
                String[] projection, 
                Bundle queryArgs)

Override this method to return the children documents contained in the requested directory. This must return immediate descendants only.

If your provider is cloud-based, and you have data cached locally, you may return the local data immediately, setting EXTRA_LOADING on Cursor extras to indicate that you are still fetching additional data. Then, when the network data is available, you can send a change notification to trigger a requery and return the complete contents. To return a Cursor with extras, you need to extend and override getExtras().

To support change notifications, you must setNotificationUri(ContentResolver, Uri) with a relevant Uri, such as buildChildDocumentsUri(String, String). Then you can call notifyChange(Uri, android.database.ContentObserver, boolean) with that Uri to send change notifications.

Parameters
parentDocumentId String: the directory to return children for.

projection String: list of DocumentsContract.Document columns to put into the cursor. If null all supported columns should be included.

queryArgs Bundle: Bundle containing sorting information or other argument useful to the provider. If no sorting information is available, default sorting will be used, which may be unordered. See QUERY_ARG_SORT_COLUMNS for details.

This value may be null.

Returns
Cursor

Throws
AuthenticationRequiredException If authentication is required from the user (such as login credentials), but it is not guaranteed that the client will handle this properly.
FileNotFoundException

See also:

queryChildDocuments

added in API level 19
Cursor queryChildDocuments (String parentDocumentId, 
                String[] projection, 
                String sortOrder)

Return the children documents contained in the requested directory. This must only return immediate descendants, as additional queries will be issued to recursively explore the tree.

Apps targeting O or higher should override queryChildDocuments(String, String[], Bundle).

If your provider is cloud-based, and you have some data cached or pinned locally, you may return the local data immediately, setting EXTRA_LOADING on the Cursor to indicate that you are still fetching additional data. Then, when the network data is available, you can send a change notification to trigger a requery and return the complete contents. To return a Cursor with extras, you need to extend and override getExtras().

To support change notifications, you must setNotificationUri(ContentResolver, Uri) with a relevant Uri, such as buildChildDocumentsUri(String, String). Then you can call notifyChange(Uri, android.database.ContentObserver, boolean) with that Uri to send change notifications.

Parameters
parentDocumentId String: the directory to return children for.

projection String: list of DocumentsContract.Document columns to put into the cursor. If null all supported columns should be included.

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. This ordering is a hint that can be used to prioritize how data is fetched from the network, but UI may always enforce a specific ordering.

Returns
Cursor

Throws
AuthenticationRequiredException If authentication is required from the user (such as login credentials), but it is not guaranteed that the client will handle this properly.
FileNotFoundException

See also:

queryDocument

added in API level 19
Cursor queryDocument (String documentId, 
                String[] projection)

Return metadata for the single requested document. You should avoid making network requests to keep this request fast.

Parameters
documentId String: the document to return.

projection String: list of DocumentsContract.Document columns to put into the cursor. If null all supported columns should be included.

Returns
Cursor

Throws
AuthenticationRequiredException If authentication is required from the user (such as login credentials), but it is not guaranteed that the client will handle this properly.
FileNotFoundException

queryRecentDocuments

added in API level 19
Cursor queryRecentDocuments (String rootId, 
                String[] projection)

Return recently modified documents under the requested root. This will only be called for roots that advertise FLAG_SUPPORTS_RECENTS. The returned documents should be sorted by COLUMN_LAST_MODIFIED in descending order, and limited to only return the 64 most recently modified documents.

Recent documents do not support change notifications.

Parameters
rootId String

projection String: list of DocumentsContract.Document columns to put into the cursor. If null all supported columns should be included.

Returns
Cursor

Throws
FileNotFoundException

See also:

queryRoots

added in API level 19
Cursor queryRoots (String[] projection)

Return all roots currently provided. To display to users, you must define at least one root. You should avoid making network requests to keep this request fast.

Each root is defined by the metadata columns described in DocumentsContract.Root, including COLUMN_DOCUMENT_ID which points to a directory representing a tree of documents to display under that root.

If this set of roots changes, you must call notifyChange(Uri, android.database.ContentObserver, boolean) with buildRootsUri(String) to notify the system.

Parameters
projection String: list of DocumentsContract.Root columns to put into the cursor. If null all supported columns should be included.

Returns
Cursor

Throws
FileNotFoundException

querySearchDocuments

added in API level 19
Cursor querySearchDocuments (String rootId, 
                String query, 
                String[] projection)

Return documents that match the given query under the requested root. The returned documents should be sorted by relevance in descending order. How documents are matched against the query string is an implementation detail left to each provider, but it's suggested that at least COLUMN_DISPLAY_NAME be matched in a case-insensitive fashion.

If your provider is cloud-based, and you have some data cached or pinned locally, you may return the local data immediately, setting EXTRA_LOADING on the Cursor to indicate that you are still fetching additional data. Then, when the network data is available, you can send a change notification to trigger a requery and return the complete contents.

To support change notifications, you must setNotificationUri(ContentResolver, Uri) with a relevant Uri, such as buildSearchDocumentsUri(String, String, String). Then you can call notifyChange(Uri, android.database.ContentObserver, boolean) with that Uri to send change notifications.

Parameters
rootId String: the root to search under.

query String: string to match documents against.

projection String: list of DocumentsContract.Document columns to put into the cursor. If null all supported columns should be included.

Returns
Cursor

Throws
AuthenticationRequiredException If authentication is required from the user (such as login credentials), but it is not guaranteed that the client will handle this properly.
FileNotFoundException

See also:

removeDocument

added in API level 24
void removeDocument (String documentId, 
                String parentDocumentId)

Removes the requested document or a document tree.

In contrast to deleteDocument(String) it requires specifying the parent. This method is especially useful if the document can be in multiple parents.

It's the responsibility of the provider to revoke grants if the document is removed from the last parent, and effectively the document is deleted.

Parameters
documentId String: the document to remove.

parentDocumentId String: the parent of the document to move.

Throws
AuthenticationRequiredException If authentication is required from the user (such as login credentials), but it is not guaranteed that the client will handle this properly.
FileNotFoundException

renameDocument

added in API level 21
String renameDocument (String documentId, 
                String displayName)

Rename an existing document.

If a different COLUMN_DOCUMENT_ID must be used to represent the renamed document, generate and return it. Any outstanding URI permission grants will be updated to point at the new document. If the original COLUMN_DOCUMENT_ID is still valid after the rename, return null.

Parameters
documentId String: the document to rename.

displayName String: the updated display name of the document. The provider may alter this name to meet any internal constraints, such as avoiding conflicting names.

Returns
String

Throws
AuthenticationRequiredException If authentication is required from the user (such as login credentials), but it is not guaranteed that the client will handle this properly.
FileNotFoundException

revokeDocumentPermission

added in API level 21
void revokeDocumentPermission (String documentId)

Revoke any active permission grants for the given COLUMN_DOCUMENT_ID, usually called when a document becomes invalid. Follows the same semantics as revokeUriPermission(Uri, int).

Parameters
documentId String

update

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

Implementation is provided by the parent class. Throws by default, and cannot be overriden.

Parameters
uri Uri: The URI to query. This can potentially have a record ID if this is an update request for a specific record.

values ContentValues: A set of column_name/value pairs to update in the database. This must not be null.

selection String: An optional filter to match rows to update.

selectionArgs String

Returns
int the number of rows affected.

This site uses cookies to store your preferences for site-specific language and display options.

Get the latest Android developer news and tips that will help you find success on Google Play.

* Required Fields

Hooray!

Browse this site in ?

You requested a page in , but your language preference for this site is .

Would you like to change your language preference and browse this site in ? If you want to change your language preference later, use the language menu at the bottom of each page.

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.