Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

startActivityForResult() vs getActivity().startActivityForResult() in Android Fragment

What the differences between startActivityForResult() vs getActivity().startActivityForResult() in Android Fragment? And what is the behaviour differences in onActivityForResult() when called in Fragment?

like image 698
j.elmer Avatar asked Dec 14 '17 06:12

j.elmer


People also ask

What is the replacement of startActivityForResult?

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.

What is purpose of startActivityForResult () function?

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).

What is use instead of startActivityForResult in Android?

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.

Can I use onActivityResult in fragment?

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() .


2 Answers

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()

like image 150
Tenten Ponce Avatar answered Oct 26 '22 01:10

Tenten Ponce


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.

like image 2
ADM Avatar answered Oct 26 '22 01:10

ADM