Search code examples
androidkotlinandroid-contentproviderandroid-10.0

Load all images from contentProvider on Android 10


I am currently using the following code to load all images from the Android contentProvider in my repository:

    override suspend fun getLocalImagePaths() = SuspendableResult.of<List<String>, Exception> {
        val result = mutableListOf<String>()
        val uri: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        val projection = arrayOf(MediaStore.MediaColumns.DATA)
        contentResolver.query(uri, projection, null, null, null)?.use {
            val dataIndex = it.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)
            while (it.moveToNext()) {
                result.add(it.getString(dataIndex))
            }
        }
        result
    }

This gets the absolute paths to all available images and it seems to work in Android 9, allthough some images can't be loaded (I am using Glide), but in Android 10 I can't load any of the image paths that are returned from the mentioned method. How could I do this?


Solution

  •     override suspend fun getLocalImagePaths() = SuspendableResult.of<List<Uri>, Exception> {
            val result = mutableListOf<Uri>()
            val uri: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            val projection = arrayOf(MediaStore.Images.Media._ID)
            contentResolver.query(uri, projection, null, null, null)?.use {
                while (it.moveToNext()) {
                    result.add(
                        ContentUris.withAppendedId(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            it.getLong(0)
                        )
                    )
                }
            }
            result
        }