registerForActivityResult in fragment

Issue

I am trying to call registerForActivityResult inside a fragment, when it finishes it just closes the fragment.

My question is how can I call this function from a fragment?

Code:

private val profileImageLauncher  registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
    if (result ! null && result.resultCode  Activity.RESULT_OK) {
        profileImageUri  result.data?.data

        try {
            profileImageUri?.let { profileImageUri ->
               if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P){
                    val bitmap: Bitmap  getBitmap(activity?.contentResolver, profileImageUri)

                    context?.let { context ->
                        Glide.with(context).load(bitmap).into(pfpIV)
                        // here it closes the fragment
                    }
                } else {
                    context?.let { context ->
                        val source  ImageDecoder.createSource(context.contentResolver, profileImageUri)
                        var bitmap  ImageDecoder.decodeBitmap(source)
                        bitmap   bitmap.copy(Bitmap.Config.ARGB_8888, true)
                        Glide.with(context).load(bitmap).into(pfpIV)
                        // here it closes the fragment
                    }
                }
            }
        } catch (e:IOException){
            e.printStackTrace()
        }
    }
}

Solution

Well the only solution I found was to use an activity, it seems that when using registerForActivityResult it returns me to the activity, not the fragment, so if you were in a fragment that wasn’t the activitie’s main/default you won’t be able to return to it, the function will return you to the main fragment for the activity since it’s technichally opening a new intent to get the information from the user (image in this case), so it has to return to the activity and cannot return to the fragment.

Answered By – Ido Barnea

Leave a Comment