Skip to content

Instantly share code, notes, and snippets.

@nieldeokar
Created March 6, 2019 17:23
Show Gist options
  • Save nieldeokar/ee21b43e76c846e8cb45cd3253a69271 to your computer and use it in GitHub Desktop.
Save nieldeokar/ee21b43e76c846e8cb45cd3253a69271 to your computer and use it in GitHub Desktop.
Fetches list of image and video Albums using content provider along with path to thumbnail of an album.
package droidninja.filepicker
import android.content.ContentResolver
import android.provider.MediaStore
import android.util.Log
/*
~ Nilesh Deokar @nieldeokar on 03/06/19 9:57 AM
*/
class GetAlbumListFromContentProvider {
private val MEDIA_TYPE_VIDEO = 3
/*
*
* mediaType could be one of
*
* public static final int MEDIA_TYPE_IMAGE = 1;
* public static final int MEDIA_TYPE_VIDEO = 3;
*
* From {@link android.provider.MediaStore}
*
*/
fun getAlbumList(mediaType: Int, contentResolver: ContentResolver) {
val countColumnName = "count"
var contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
if (mediaType == MEDIA_TYPE_VIDEO) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
}
val projection = arrayOf(MediaStore.Images.ImageColumns.BUCKET_ID, MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, MediaStore.Images.ImageColumns.DATE_TAKEN, MediaStore.Images.ImageColumns.DATA)
val bucketGroupBy = "1) GROUP BY ${MediaStore.Images.ImageColumns.BUCKET_ID}, (${MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME}"
val bucketOrderBy = MediaStore.Images.Media.DATE_MODIFIED + " DESC"
val cursor = contentResolver.query(contentUri, projection, bucketGroupBy, null, bucketOrderBy)
/* This creates a query :
SELECT bucket_id, bucket_display_name, datetaken, _data FROM images WHERE (1)
GROUP BY bucket_id,(bucket_display_name) ORDER BY date_modified DESC
*/
if (cursor != null) {
while (cursor.moveToNext()) {
val bucketId = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.BUCKET_ID))
val name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME))
val path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)) // Thumb image path
val selection = MediaStore.Images.Media.BUCKET_ID + "='" + bucketId + "'"
val countCursor = contentResolver.query(contentUri, arrayOf("$countColumnName(*) AS $countColumnName"), selection, null, null)
var count = 0
if (countCursor != null) {
countCursor.moveToFirst()
count = countCursor.getInt(countCursor.getColumnIndexOrThrow(countColumnName))
countCursor.close()
}
Log.d("AlbumScanner", "bucketId : $bucketId | name : $name | count : $count | path : $path")
}
cursor.close()
}
}
}
@aisnote
Copy link

aisnote commented Mar 4, 2021

new android with kotlin, can not use this way now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment