What the differences between startActivityForResult()
vs getActivity().startActivityForResult()
in Android Fragment? And what is the behaviour differences in onActivityForResult()
when called in Fragment?
Among the contracts available, the StartActivityForResult contract is the replacement to the startActivityForResult . The callback is to be called once the activity result is available.
By the help of android startActivityForResult() method, we can send information from one activity to another and vice-versa. The android startActivityForResult method, requires a result from the second activity (activity to be invoked).
But recently startActivityForResult() method is deprecated in AndroidX. Android came up with ActivityResultCallback (also called Activity Results API) as an alternative for it. Normal way to send and receive data by startActivityForResult() To implement it by Activity Results API you can replace this code by following.
Android Intent Getting a result from Activity to Fragment note that you should not call getActivity(). startActivityForResult() as this will take the result back to the Fragment 's parent Activity . Receiving the result can be done using the Fragment 's method onActivityResult() .
startActivityForResult()
must handle it from the fragment
's onActivityForResult()
getActivity().startActivityForResult()
must handle it from the activity
's onActivityForResult()
Basically:
If you're on a fragment
and you want to handle the result on the fragment
, use onActivityForResult()
, otherwise if you want to handle it from the activity
of the fragment, use getActivity.startActivityForResult()
startActivityForResult from fragment call startActivityForResult of its container Activity. So for Fragment:-
Call startActivityForResult(Intent, int) from the fragment's containing Activity.
Whereas when you use it in fragment directly some certain changes can be made on request code.And you will get modified request code in onActivityresult(), Cause i have faced some problem with modified request code recently . You can have a look into This Thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With