android - 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 .
解决方案
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
.
推荐阅读
- c - sizeof 在某些情况下的行为是否不同
- python - 如何根据另一列的特定值从一列中删除 NaN
- node.js - Google Chrome Labs ndb - 安装但不运行
- java - 如何在运行时自动打印Java函数的所有参数值
- android-studio - Android Studio 4.1.2 - Dart 和 Flutter 未安装在“flutter doctor”中
- javascript - 在没有 apex only javascript 控制器的闪电网络组件上创建任务?
- html - CSS:如何从下拉菜单中舍入选择框?
- java - 我的 android studio 制作的 apk 无法正常工作
- r - 从 GitHub 下载 bibtex 到 R
- react-redux - 在 axios 拦截器中调用 redux 操作