I want the user to pick an image from the device then deal with that as a Bitmap myself, how do I achieve this with the help of content providers?

115 views Asked by At

I have found several methods to achieve this but none of those seem straight forward and I don't understand the code in many of them. I read a little about content resolver, content provider and cursor recently and it seems that is the best practice to get a file from the user that's stored on the device. Right now I am using this but it seems weird:

            val selectedImageUri: Uri = data.data!!
            val inputStream = contentResolver.query(selectedImageUri, Android.provider)
            bitmap = BitmapFactory.decodeStream(inputStream)

It uses a contnt resovler but with an input stream? I think that's a Java thing and not the best practice to achieve this on android. There is also this function

    fun getBitmapFromURI(uri: Uri): Bitmap? {
         val filePathColumn = arrayOf(MediaStore.Images.Media.DATA)
         val cursor: Cursor? =
             this.contentResolver.query(uri, filePathColumn, null, null, null)
         if (cursor != null) {
             cursor.moveToFirst()
             val columnIndex = cursor.getColumnIndex(filePathColumn[0])
             val fImage = File(cursor.getString(columnIndex))
             cursor.close()
             val o2 = BitmapFactory.Options()

             return BitmapFactory.decodeFile(fImage.absolutePath, o2)
         }
         return null
     }

I copied this from another thread on SO but again it feels so weird because i don't understand why we're asking the cursor to go to the first whatever why the rest of the parameters are passedi in null. Can someoen provide me with the best code that follows all the best practices and does things in a very efficient way?

0

There are 0 answers