Search code examples
androidkotlinonactivityresult

onActivityResult is not called (Kotlin)


I need help. On my onCreate() I have this code:

    takePhotoDialog = DialogGetPhotoFrom.getInstance().apply {
        setListener(object : DialogGetPhotoFrom.DialogListener {
            override fun onTakeFromGallery() {
                Log.v("ProjectDetails", "onTakeFromGallery called")
                val intent = Intent().apply {
                    type = "image/*"
                    action = Intent.ACTION_GET_CONTENT
                }
                startActivityForResult(Intent.createChooser(intent, "Select Image"), REQUEST_PICK_IMAGE)
            }

            override fun onTakePhoto() {
                dispatchTakePictureIntent()
            }
        })
    }

    projectDetails_pickImage.setOnClickListener { takePhotoDialog?.show(supportFragmentManager) }

An on my onActivityResult, I wrote:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    when (requestCode) {
        REQUEST_PICK_IMAGE -> {
            Log.v("ProjectDetails", "REQUEST_PICK_IMAGE called")
            if (resultCode == Activity.RESULT_OK) {
                if (data != null) {
                    try {
                        val inputStream = contentResolver.openInputStream(data.data)
                        val bitMap = BitmapFactory.decodeStream(inputStream)
                        projectDetails_image.setImageBitmap(bitMap)
                        // TODO Save image URI to database
                    } catch (e: Exception) {
                        Toast.makeText(this, "Can't set background.", Toast.LENGTH_SHORT).show()
                    }
                } else {
                    Log.v("ProjectDetails", "data is null")
                }
            }
        }
    }
}

The problem is, onActivityResult() doesn't fire when an image is selected. What should I do?


Solution

  • Solved it! The solution is to put the codes inside my onTakeGallery() function to a function that belongs to the Activity class. So my code will look like this:

    takePhotoDialog = DialogGetPhotoFrom.getInstance().apply {
        setListener(object : DialogGetPhotoFrom.DialogListener {
            override fun onTakeFromGallery() {
                dispatchSelectFromGalleryIntent()
            }
    
            override fun onTakePhoto() {
                dispatchTakePictureIntent()
            }
        })
    }
    
    projectDetails_pickImage.setOnClickListener { 
        takePhotoDialog?.show(supportFragmentManager)
    }
    

    And the extracted codes goes here:

    private fun dispatchSelectFromGalleryIntent() {
        val intent = Intent().apply {
            type = "image/*"
            action = Intent.ACTION_GET_CONTENT
        }
        startActivityForResult(Intent.createChooser(intent, "Select Image"), REQUEST_PICK_IMAGE)
    }