I have been trying to implement a feature in my app using Kotlin that lets a user upload an image after clicking on an empty image slot:
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.get_started)
    val imageView = findViewById<View>(R.id.userPhoto) as ImageView
    imageView.setOnClickListener{
        selectImage()
    }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (resultCode == RESULT_OK) {
        Log.d("demo", "data: " + data!!.data)
        val bitmap = getPath(data!!.data)
        Log.d("demo", "passed this point 4")
        imageView!!.setImageBitmap(bitmap)
    }
}
private fun getPath(uri: Uri?): Bitmap {
    val projection = arrayOf(MediaStore.Images.Media._ID)
    Log.d("demo", "projection: " + projection.contentDeepToString())
    val cursor = contentResolver.query(uri!!, projection, null, null, null)
    val columnIndex = cursor!!.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
    Log.d("demo", "columnIndex: $columnIndex")
    Log.d("demo", "cursor: $cursor")
    cursor.moveToFirst()
    Log.d("demo", "cursor: $cursor")
    val filePath = cursor.getString(columnIndex)
    // cursor.close()
    Log.d("demo", "filepath: $filePath")
    // Convert file path into bitmap image using below line.
    return BitmapFactory.decodeFile(filePath)
}
private fun selectImage() {
    val intent = Intent()
    intent.type = "image/*"
    intent.action = Intent.ACTION_GET_CONTENT
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE)
    }
Everything seems to work fine except in the getPath() function where I keep getting null when I select an image from the android gallery. Does anyone know what might be causing this? The java version of the code was gotten from here
Edit: It turns out the problem is from the BitmapFactory.decodeFile(filePath) line which keeps returning Null
Edit2: I was able to get it working by getting rid of getPath() and using the following code for onActivityResult():
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            Log.d("demo", "passed this point 3")
            Log.d("demo", "data: " + data!!.data)
            val `is` = contentResolver.openInputStream(data!!.data!!)
            val bitmap = BitmapFactory.decodeStream(`is`)
            Log.d("demo", "passed this point 4")
            imageView?.setImageBitmap(bitmap)
            imageView?.bringToFront()
        }
    }