onActivityResult deprecated, is there alternative (KOTLIN)

1.3k Views Asked by At

Currently I am working on a project for my college, and i have discovered that onActivityResult is deprecated. What can be done to handle it?

This is my code that troubles me

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            val result = CropImage.getActivityResult(data)
            if (resultCode == RESULT_OK) {
                image = result.uri
                Glide.with(this).load(image).into(binding.imgPick)
            } else {
                Snackbar.make(
                    binding.root,
                    "Image not selected",
                    Snackbar.LENGTH_SHORT
                ).show()
            }
        }

    }

I tried to find a solution on stackoverflow and already tried to implement couple of thing but with no luck.

3

There are 3 best solutions below

0
manish_cjsvm On

You can use the following way :

fun openActivityForResult() {
        startForResult.launch(Intent(this, AnotherActivity::class.java))
    }


    val startForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { 
    result: ActivityResult ->
        if (result.resultCode == Activity.RESULT_OK) {
            val intent = result.data
            // Handle the Intent
            //do stuff here
        }
    }
0
m7s On

You can use this in activity or fragment.

First define intent result launcher.

var picker: ActivityResultLauncher<Intent>

then

picker = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {

            if (it.resultCode == Activity.RESULT_OK && it.data != null) {

               //add your code here
            }
        }

And now launch your activity.

 val intent = Intent(context, ImagePickerActivity::class.java)
        picker.launch(intent)
0
Nrohpos On

If you want to explore more there is a lib for that here

If you use Coroutines, you want synchronized like this.

val activityResult: ActivityResult = TedOnActivityResult.with().startActivityForResult(intent)

If you use RxJava, you want chaining like this.

 AA()
  .filter(...)
  .subscribeOn(...)
  .observeOn(...)
  .subscribe(...);