首页 > 解决方案 > How to read Image from a specific folder on Android 10 using MediaStore

问题描述

I'm trying to read Image from DCIM/Folder_Name(the location where the app saves image ).I need to display the image like a gallery only from that Folder_Name. I tried using MediaStore with query and cursor . But I come out only with bucket names which is the name of the folder containing images . I don't know how to filter only Folder_name and it's content inside . Here is my code.

val projection= arrayOf(MediaStore.Images.Media.BUCKET_DISPLAY_NAME, MediaStore.Images.Media.BUCKET_ID,
            MediaStore.Images.Media.BUCKET_ID)
val cursor: Cursor? = contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,projection,"",null,MediaStore.Images.Media.DEFAULT_SORT_ORDER)
cursor?.moveToFirst()
if(cursor!=null){
    while (!cursor.isAfterLast){
        Log.d("CURSOr","Name "+cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME)))
        cursor.moveToNext()
    }
}
cursor?.close()

How to use selection query in Android 10 for select desire folders content Thank you .

标签: androidkotlinstoragemediastoreandroid-10.0

解决方案


I did a projection on RELATIVE_PATH constant instead of BUCKET_DISPLAY_NAME (which just gives you the name of last folder) and a selection of LIKE DCIM/Test% using the below code to filter out the results from DCIM/Test folder.

val projection = arrayOf(_ID, DATE_ADDED, BUCKET_DISPLAY_NAME, RELATIVE_PATH)
val selection = "${MediaStore.MediaColumns.RELATIVE_PATH} LIKE ?"
val selectionArgs = arrayOf("DCIM/Test%") // Test was my folder name
val sortOrder = "$DATE_ADDED DESC"

app.contentResolver.query(
    EXTERNAL_CONTENT_URI,
    projection,
    selection,
    selectionArgs,
    sortOrder
)?.use {
    val id = it.getColumnIndexOrThrow(_ID)
    val bucket = it.getColumnIndexOrThrow(BUCKET_DISPLAY_NAME)
    val date = it.getColumnIndexOrThrow(DATE_ADDED)
    val path = it.getColumnIndexOrThrow(RELATIVE_PATH)
    while (it.moveToNext()) {
        // Iterate the cursor
    }
}

The only disadvantage of this approach is that RELATIVE_PATH is available for API level 29 (Q) and above.

Edit: Changed the selection args from %DCIM/Test% to DCIM/Test% as pointed out by Alejandro Gomez. The prior will match to any DCIM folder (including the system default) eg. My/DCIM/Test/Sample.jpg will also be in the output alongside DCIM/Test/Sample.jpg.


推荐阅读