skip to Main Content

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

Answers


  1. 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
            }
        }
    
    Login or Signup to reply.
  2. 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)
    
    Login or Signup to reply.
  3. 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(...);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search