我想使用MediaStore将厨房中的所有图片加载到我的应用程序中.媒体专栏.数据,但它已被弃用.那么,加载它们的另一种方式是什么呢?

我现在使用这段代码,但正如我所说,它已被弃用:

fun getAllShownImagesPath(activity: Activity): MutableList<String> {
    val uri: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    val cursor: Cursor?
    val columnIndexData: Int
    val listOfAllImages: MutableList<String> = mutableListOf()
    val projection = arrayOf(MediaStore.MediaColumns.DATA)
    var absolutePathOfImage: String
    cursor = activity.contentResolver.query(uri, projection, null, null, null)
    if (cursor != null) {
        columnIndexData = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)
        while (cursor.moveToNext()) {
            absolutePathOfImage = cursor.getString(columnIndexData)
            listOfAllImages.add(absolutePathOfImage)
        }
        cursor.close()
    }
    return listOfAllImages
}

推荐答案

我能够取代MediaStore.媒体专栏.数据有自己的文件ID(难以置信,文件有ID)并正确构造其URI,如下所示:

fun getAllShownImagesPath(activity: Activity): MutableList<Uri> {
    val uriExternal: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    val cursor: Cursor?
    val columnIndexID: Int
    val listOfAllImages: MutableList<Uri> = mutableListOf()
    val projection = arrayOf(MediaStore.Images.Media._ID)
    var imageId: Long
    cursor = activity.contentResolver.query(uriExternal, projection, null, null, null)
    if (cursor != null) {
        columnIndexID = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
        while (cursor.moveToNext()) {
            imageId = cursor.getLong(columnIndexID)
            val uriImage = Uri.withAppendedPath(uriExternal, "" + imageId)
            listOfAllImages.add(uriImage)
        }
        cursor.close()
    }
    return listOfAllImages
}

and then with Uri you build it in your Views!

Kotlin相关问答推荐

在Mapstruct中重用@映射定义

将带大括号和不带大括号的Lambda值赋给@Composable函数

用A*搜索算法解决特修斯和米诺陶尔难题

用vararg替换列表的设计弃用警告

Kotlin接口方法默认值&;可传递依赖项

Webpack 配置未应用于 kotlin 多平台react 项目

MyType.()在 Kotlin 中是什么意思?

Kotlin 中的as Long和.toLong()有什么区别?

Kotlin 有垃圾收集器吗?如果是这样,它基于哪种算法?

将 jetpack compose 添加到现有元素

如何修复 ViewPager2 中的Design assumption violated错误?

Kotlin 顶级函数与对象函数

如何在 Kotlin 中判断数组类型(不是泛型类型)

Firebase 权限被拒绝

Kotlin内联扩展属性

Android 与 Kotlin - 如何使用 HttpUrlConnection

用于代码生成的ANTLR工具版本4.7.1与当前运行时版本4.5.3不匹配

导航架构组件 - 未生成 DestinationFragmentArgs

Kotlin for assertThat(foo, instanceOf(Bar.class))

如何在 Fragment 中使用 Anko DSL?