6

When using androids new activity result API, the callback is only firing once for me.

class MyFragment : Fragment() {
   private val intentLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
      if (result.resultCode == Activity.RESULT_OK) {
         ...
      }
   }
}

private fun onClick(id: Long) {
  val intent = Intent(context, MyActivity::class.java)
  intent.putExtra(MyActivity.ID_EXTRA, id)
  intentLauncher.launch(intent)
}

On first click the fragment launches the activity, and on activity finish the result is passed back correctly. However when the fragment launches the activity again, the activity sets the result and calls finish. However the result callback in the fragment is not fired again.

Also noticed that I didn't need to include:

implementation 'androidx.activity:activity-ktx:1.4.0'
implementation 'androidx.fragment:fragment-ktx:1.4.1'

Does the new activity result API come along with some other dependency? Wondering if something else weird is going on w/ the versions I am pulling in?

EDIT:

Its important to note that this is only happening when using the new activity result api from a fragment to launch a new activity. I do not see the same behavior when launching from an activity. Is there something I need to do differently for fragments?

lostintranslation
  • 23,756
  • 50
  • 159
  • 262

1 Answers1

3

Just add launchIntent.setFlags(0); before startActivityForResult().

This reference may help you.

Ryan M
  • 18,333
  • 31
  • 67
  • 74
Mukund Jogi
  • 1,329
  • 5
  • 18