val contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
Projections
Image ID and URI
val projections = arrayOf( MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA)
contentResolver.query(contentUri, projections, null, null, null)?.use { cursor -> if (cursor.moveToFirst()) { val imageIdIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns._ID) val imageUriIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA) do { val id = cursor.getString(imageIdIndex) val imageUri = Uri.parse(cursor.getString(imageUriIndex)) } while (cursor.moveToNext()) // cursor.close() }}
Distinct Bucket Name
val projections = arrayOf( "DISTINCT ${MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME}")
contentResolver.query(contentUri, projections, null, null, null)?.use { cursor -> if (cursor.moveToFirst()) { val bucketNameIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME) val bucketName = cursor.getString(bucketNameIndex) }}
Group By
val projections = arrayOf( MediaStore.Images.ImageColumns.BUCKET_ID, MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, "COUNT(" + MediaStore.Images.ImageColumns._ID + ") AS image_count")val groupBy = "1) GROUP BY ${MediaStore.Images.ImageColumns.BUCKET_ID}, (${MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME}"contentResolver.query(contentUri, projections, groupBy, null, null)?.use { cursor -> if (cursor.moveToFirst()) { val bucketIdIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.BUCKET_ID) val nameIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME) val countIndex = cursor.getColumnIndexOrThrow("image_count") do { val bucketId = cursor.getString(bucketIdIndex) val bucketName = cursor.getString(nameIndex) val imageCount = cursor.getLong(countIndex) } while (cursor.moveToNext()) } // cursor.close()}
Where Condition (Selection), Sort Order and Limit
val bucketId = ...val projections = arrayOf( MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA)val selection = "${MediaStore.Images.ImageColumns.BUCKET_ID} == ?"val selectionArgs = arrayOf( bucketId)val sortOrder = "${MediaStore.Images.ImageColumns.DATE_TAKEN} DESC LIMIT 1"contentResolver.query(contentUri, projections, selection, selectionArgs, sortOrder)?.use { cursor -> if (cursor.moveToFirst()) { val imageUriIndex = imageCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA) val imageUri = Uri.parse(imageCursor.getString(imageUriIndex)) } // cursor.close()}
References: