Skip to content
Tutorials Center
My learning

Topics

Lesson 72 of 104 ยท Local Data

Content Providers and ContentResolver

Learn Android content providers: content URIs, ContentResolver query and insert, MediaStore and Contacts, permissions, writing your own provider with UriMatcher, and FileProvider.

An Android app's data is private to it: its files and databases are locked inside the app sandbox, and another app cannot open them. Yet phones are full of data that should be shared on purpose: your contacts, the photos in the gallery, the calendar, the download list. Android's controlled door for this is the content provider, the fourth of the four app components. A provider hides how data is stored and offers a uniform, permission-guarded interface of URIs and tables.

You will use providers far more than you write them. Reading photos goes through MediaStore, reading contacts through the Contacts provider, sharing a file with the camera app through FileProvider. You write your own only when other apps must read your data. This lesson shows the vocabulary (content URIs, ContentResolver, Cursor), reads from the system providers, shows how a provider is built and secured, and finishes with FileProvider, the one custom provider almost every app declares. The Android classes cannot run here, so the real code is read-only; the TryIts are plain-Kotlin stand-ins that model URI parsing, a resolver with a provider, and a file-sharing configuration.

Content URIs

Everything in the provider world is addressed by a content URI:

Text
content://com.example.notes.provider/notes/42
\_____/ \_________________________/ \____/ \_/
scheme          authority            path   id
  • content:// is the scheme that marks "ask a provider".
  • The authority names the provider, usually a reverse-domain string declared in the manifest. The system uses it to find the right app.
  • The path names a table or kind of data; a trailing number (an _ID) selects one row.

Some well-known URIs are ContactsContract.Contacts.CONTENT_URI, MediaStore.Images.Media.EXTERNAL_CONTENT_URI and Settings.System.CONTENT_URI. You can think of them as REST endpoints for local data, and of ContentResolver as the client.

Reading with ContentResolver

Your app never talks to a provider class directly. It asks its ContentResolver (context.contentResolver), which finds the provider that owns the authority, possibly in another process, and forwards the call. The four operations mirror SQL tables: query, insert, update and delete.

Kotlin
// read-only example: read contacts (needs READ_CONTACTS granted at runtime)
fun loadContactNames(context: Context): List<String> {
    val names = mutableListOf<String>()
    val projection = arrayOf(ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME_PRIMARY)
    val selection = "${ContactsContract.Contacts.DISPLAY_NAME_PRIMARY} LIKE ?"
    val args = arrayOf("A%")
    val sort = "${ContactsContract.Contacts.DISPLAY_NAME_PRIMARY} ASC"

    context.contentResolver.query(
        ContactsContract.Contacts.CONTENT_URI, projection, selection, args, sort,
    )?.use { cursor ->                              // use { } closes the cursor
        val nameIndex = cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY)
        while (cursor.moveToNext()) {
            names += cursor.getString(nameIndex)
        }
    }
    return names
}

Read the call carefully, because it has the same shape everywhere:

  • projection: the columns you want. Ask only for what you need.
  • selection and selectionArgs: a SQL WHERE clause with ? placeholders and the values separately. Never concatenate user input into the selection string; it is the same SQL-injection risk as anywhere else.
  • sortOrder: an ORDER BY clause.
  • The result is a Cursor, a pointer over rows. Move it with moveToNext(), read columns by index, and close it (use { }). It can be null.

Run this on a background thread (a coroutine on Dispatchers.IO), since a provider can be slow and may live in another process. See Coroutines on Android.

Writing and the system providers

Kotlin
// read-only example: insert into MediaStore (a photo you created), no permission on API 29+
val values = ContentValues().apply {
    put(MediaStore.Images.Media.DISPLAY_NAME, "sunset.jpg")
    put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
    put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/MyApp")
}
val uri = context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
uri?.let { context.contentResolver.openOutputStream(it)?.use { out -> bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out) } }

Three system providers matter most:

  • MediaStore indexes photos, videos and audio. With scoped storage (Android 10 and higher) your app can add its own files without permission, but reading other apps' media needs READ_MEDIA_IMAGES, READ_MEDIA_VIDEO or READ_MEDIA_AUDIO on Android 13 and higher (READ_EXTERNAL_STORAGE before). Better still, use the photo picker (ActivityResultContracts.PickVisualMedia), which needs no permission at all, see Runtime Permissions and Files and Storage.
  • ContactsContract requires the dangerous permissions READ_CONTACTS and WRITE_CONTACTS at runtime. Ask only if you really need them, since many users refuse. Where possible, launch the contact picker with an intent instead.
  • CalendarContract, Telephony (restricted) and Settings exist too, each with its own permissions.

A ContentResolver can also tell you when data changes. Register a ContentObserver with registerContentObserver(uri, true, observer) and reload when it fires; Room does the same thing internally for its invalidation tracking.

The first stand-in models a resolver. It parses content:// URIs, routes by authority to a registered provider and runs query and insert against an in-memory table, with projection, a selection argument and a sort order.

Kotlin A ContentResolver and a provider (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Writing your own provider

You rarely need to. If the data is for your own app, use Room directly. Write a provider when you must share structured data with other apps, plug into a system feature that expects one (search suggestions, a sync adapter, an account), or expose files securely (the FileProvider case below).

A provider subclasses ContentProvider and implements six methods: onCreate(), query(), insert(), update(), delete() and getType(). A UriMatcher turns incoming URIs into codes so one when can decide what to do. A usual design is two patterns per table: the whole table (notes) and a single row (notes/#, where # matches a number).

Kotlin
// read-only example: a Room-backed provider
class NotesProvider : ContentProvider() {

    private lateinit var db: NotesDatabase

    private val matcher = UriMatcher(UriMatcher.NO_MATCH).apply {
        addURI(AUTHORITY, "notes", NOTES)
        addURI(AUTHORITY, "notes/#", NOTE_ID)
    }

    override fun onCreate(): Boolean {            // runs on the main thread at startup: keep it light
        db = NotesDatabase.get(context!!)
        return true
    }

    override fun query(
        uri: Uri, projection: Array<String>?, selection: String?,
        selectionArgs: Array<String>?, sortOrder: String?,
    ): Cursor? {
        val cursor = when (matcher.match(uri)) {
            NOTES -> db.query(SupportSQLiteQueryBuilder.builder("notes")
                .columns(projection).selection(selection, selectionArgs).orderBy(sortOrder).create())
            NOTE_ID -> db.query(SupportSQLiteQueryBuilder.builder("notes")
                .columns(projection).selection("id = ?", arrayOf(ContentUris.parseId(uri).toString())).create())
            else -> throw IllegalArgumentException("Unknown URI: $uri")
        }
        cursor.setNotificationUri(context!!.contentResolver, uri)   // observers are told on change
        return cursor
    }

    override fun getType(uri: Uri): String? = when (matcher.match(uri)) {
        NOTES -> "vnd.android.cursor.dir/vnd.com.example.note"
        NOTE_ID -> "vnd.android.cursor.item/vnd.com.example.note"
        else -> null
    }

    // insert(), update(), delete() follow the same pattern and call
    // context.contentResolver.notifyChange(uri, null) after changing data.

    companion object {
        const val AUTHORITY = "com.example.notes.provider"
        private const val NOTES = 1
        private const val NOTE_ID = 2
    }
}
XML
<!-- read-only example: declaring and protecting the provider -->
<provider
    android:name=".NotesProvider"
    android:authorities="com.example.notes.provider"
    android:exported="true"
    android:readPermission="com.example.notes.READ_NOTES"
    android:writePermission="com.example.notes.WRITE_NOTES" />

Security is the whole point:

  • android:exported="false" keeps the provider private to your app, which is correct for helpers like FileProvider. Export only what you mean to share.
  • Use readPermission and writePermission (or one permission) to restrict access, and the grantUriPermissions feature to give another app temporary access to one URI instead of the whole provider.
  • Treat selection and projection from other apps as untrusted. Build queries with arguments and consider a whitelist of columns, otherwise a caller can read or filter by columns you never meant to expose. Never concatenate strings into SQL.
  • Since Android 11, an app that wants to talk to another app's custom provider declares it in <queries> in its own manifest because of package visibility (see Intents).

The second stand-in is the piece in the middle of a real provider: a small UriMatcher that turns paths into codes, the routing a provider does before it touches data.

Kotlin UriMatcher: from a path to a code (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

FileProvider: sharing files safely

Sometimes your app must hand a file to another app: a photo for the camera to write, a PDF for a viewer, an image to attach to an email. Passing a raw file:// path is banned (since Android 7 the system throws FileUriExposedException), because it would expose your private storage and the other app has no permission to open it. The solution is FileProvider, a ready-made provider in AndroidX that maps a file to a content:// URI and grants the receiving app temporary access to exactly that file.

Three steps set it up.

XML
<!-- read-only example: 1. declare it in the manifest -->
<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>
XML
<!-- read-only example: 2. res/xml/file_paths.xml lists the folders that may be shared -->
<paths>
    <cache-path name="shared_images" path="images/" />
    <files-path name="exports" path="exports/" />
</paths>
Kotlin
// read-only example: 3. create a URI and grant access
val file = File(context.cacheDir, "images/receipt.png")
val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)

val send = Intent(Intent.ACTION_SEND).apply {
    type = "image/png"
    putExtra(Intent.EXTRA_STREAM, uri)
    addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)      // temporary read access for the receiver
}
context.startActivity(Intent.createChooser(send, "Share receipt"))

The XML file is the safety net: only files inside the listed folders can be turned into URIs, and the URI contains the name alias instead of the real path, so the receiver cannot learn your storage layout. The permission lasts until the receiving activity finishes, or you revoke it. In Compose, the camera flow uses the same URI with ActivityResultContracts.TakePicture(); see the permissions lesson for the launcher pattern.

The final stand-in models that mapping: a restricted set of shareable folders, an alias in the URI and a temporary grant that is checked on every open.

Kotlin FileProvider mapping and temporary grants (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The private database is refused because it is outside every configured root, the unrelated app is refused because it never got a grant, and the mail app loses access when the grant is revoked. Those are the three guarantees you get from a few lines of XML.

Common mistakes

  • Running query on the main thread. A slow provider freezes the UI; use a coroutine on Dispatchers.IO.
  • Forgetting to close the Cursor (or not using use { }). It leaks native resources.
  • Concatenating user input into the selection. Use ? placeholders and selectionArgs.
  • Exporting a provider that should be private. Export only what you share, and protect it with permissions.
  • Using Uri.fromFile() and file:// URIs to share files. Use FileProvider.
  • Skipping FLAG_GRANT_READ_URI_PERMISSION. The receiving app then cannot open the URI.
  • Asking for READ_CONTACTS or storage permissions when a picker would do. Intents and the photo picker need no permission.
  • Making a provider just to read your own database. Use Room.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In content://com.example.notes.provider/notes/42, what is com.example.notes.provider?

    The authority names the provider; the path (notes) names the table and the trailing number selects a row.
  2. 2. Why do ContentResolver.query calls use '?' in the selection and a separate selectionArgs array?

    Arguments are bound as values, so they cannot change the structure of the query. Concatenating strings opens the door to SQL injection.
  3. 3. What problem does FileProvider solve?

    file:// URIs expose your storage and are rejected on modern Android. FileProvider maps a file to a content URI and the grant flag gives the receiver temporary read access.
  4. 4. When should you write your own ContentProvider?

    For your own app's data use Room directly. A provider is for sharing across the app boundary.
  5. 5. Which is the best way to let the user pick a photo on Android 13 and later?

    The photo picker returns only the photos the user chooses and needs no storage permission.

Summary

  • A content provider exposes data to other apps (and your own code) through content URIs; ContentResolver is the client with query, insert, update and delete.
  • A content URI has a scheme, an authority that names the provider, a path for the table and an optional row id.
  • Queries use a projection, a selection with ? placeholders plus arguments, and a sort order, return a Cursor that you must close, and belong off the main thread.
  • MediaStore, Contacts and the other system providers have their own permissions; prefer pickers (photo picker, contact picker intents) when you can.
  • A custom provider implements query, insert, update, delete and getType, routes with UriMatcher, and is protected with exported, permissions and URI grants.
  • FileProvider shares files by mapping them to content:// URIs from an allowed list of folders and granting temporary access.
  • The Android code is read-only; the TryIts model a resolver and provider, a UriMatcher and FileProvider's mapping and grants.

Next: Files and Storage