onActivityResult is not being called in Fragment
The hosting activity overrides onActivityResult()
, but it did not make a call to super.onActivityResult()
for unhandled result codes. Apparently, even though the fragment is the one making the startActivityForResult()
call, the activity gets the first shot at handling the result. This makes sense when you consider the modularity of fragments. Once I implemented super.onActivityResult()
for all unhandled results, the fragment got a shot at handling the result.
And also from @siqing answer:
To get the result in your fragment make sure you call startActivityForResult(intent,111);
instead of getActivity().startActivityForResult(intent,111);
inside your fragment.
I think you called getActivity().startActivityForResult(intent,111);
. You should call startActivityForResult(intent,111);
.
Option 1:
If you're calling startActivityForResult()
from the fragment then you should call startActivityForResult()
, not getActivity().startActivityForResult()
, as it will result in fragment onActivityResult().
If you're not sure where you're calling on startActivityForResult()
and how you will be calling methods.
Option 2:
Since Activity gets the result of onActivityResult()
, you will need to override the activity's onActivityResult()
and call super.onActivityResult()
to propagate to the respective fragment for unhandled results codes or for all.
If above two options do not work, then refer to option 3 as it will definitely work.
Option 3:
An explicit call from fragment to the onActivityResult function is as follows.
In the parent Activity class, override the onActivityResult() method and even override the same in the Fragment class and call as the following code.
In the parent class:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.dualPane);
fragment.onActivityResult(requestCode, resultCode, data);
}
In the child class:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// In fragment class callback
}
In case you don't know fragments in your activity just enumerate them all and send activity result arguments:
//Java
// In your activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
//Kotlin
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
for (fragment in supportFragmentManager.fragments) {
fragment.onActivityResult(requestCode, resultCode, data)
}
}