Interview frequency: …
Short answer
It is a central component for managing and sharing structured data between different apps securely through an interface based on Uri paths.
Explanation
A ContentProvider works as a secure intermediary between apps, wrapping the internal database or files and offering a standard CRUD interface. You need it when you want to share your app's data with external apps, when dealing with system data such as Contacts and MediaStore, or to use FileProvider to share files securely without exposing the real storage path.
Code example
val cursor = contentResolver.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME),
null, null, null
)
cursor?.use {
while (it.moveToNext()) {
val name = it.getString(it.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME))
}
}Common mistakes
- Running ContentResolver queries on the main thread, causing UI freezes and sluggish scrolling.
- Not closing the Cursor when done with it, causing a leak of database references and cursor memory.