MediaStore.MediaColumns.DATA is deprecated, and I want to load images from gallery to my app

前端 未结 4 1699
遥遥无期
遥遥无期 2021-02-03 11:05

I want to load all the pictures from the galley to my app by using MediaStore.MediaColumns.DATA , but it is deprecated. So, what is the other way to load them?

I use this

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-03 11:23

    I managed to come up with the following solution, its kind of an addition to the previous answer

    but there I still couldn't load images with the obtained Uri. Documentation suggested to use openFileDescriptor() which I did and then decoded images' bitmaps from it:

    override fun loadImagesFromStorage(): List {
    
        val uri: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        val cursor: Cursor?
        val columnIndexId: Int
        val listOfAllImages = mutableListOf()
        val projection = arrayOf(MediaStore.Images.Media._ID)
        cursor = context.contentResolver
            .query( uri, projection, null, null, null)
    
        if ( cursor != null ){
            columnIndexId = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
            while (cursor.moveToNext()){
    
                val contentUri = ContentUris.withAppendedId(uri, cursor.getLong(columnIndexId))
    
                //here I open FileDescriptor and then decode it into Bitmap
                var image: Bitmap
                context.contentResolver.openFileDescriptor(contentUri, "r").use { pfd ->
                    if( pfd != null ){
                        image = BitmapFactory.decodeFileDescriptor(pfd.fileDescriptor)
                        listOfAllImages.add(AdapterImage(image))
                    }
                }
    
            }
            cursor.close()
        }
    
        return listOfAllImages
    }
    

    P.S. My method will return a list of AdapterImage objects that I use later in app but you can put anything you need there at this point

提交回复
热议问题