Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onActivityResult For Fragment

I currently have a base activity which is hosting a single fragment. Inside the fragment I have a method which starts the contact chooser.

private void chooseContacts() {     Intent pickContactIntent = new Intent(Intent.ACTION_PICK,      ContactsContract.Contacts.CONTENT_URI);     pickContactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);     startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST); } 

When this activity returns how should I capture the results. I have tried adding a

@Override public void onActivityResult(int requestCode, int resultCode, Intent data) {     super.onActivityResult(requestCode, resultCode, data);     //Handle Code } 

to both my base Activity and the fragment but neither method are being triggered. If possible I would like to have the fragment handle the return so as not to muddy up the activity.

Please let me know what the best practice is in this situation.

Update:

if I change:

startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST); 

to

getActivity().startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST); 

then it works, but other posts have made me think that is incorrect.

like image 659
Nath5 Avatar asked Nov 18 '13 02:11

Nath5


People also ask

Can we use onActivityResult in fragment?

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.

How can I call onActivityResult of fragment from activity in Android?

Within your fragment, you need to call: startActivityForResult(myIntent, MY_INTENT_REQUEST_CODE); where myIntent is the intent you already defined, and MY_INTENT_REQUEST_CODE is the int constant you defined in this fragment as a global variable as the request code for this intent.

What is the use of onActivityResult in Android?

The android startActivityForResult method, requires a result from the second activity (activity to be invoked). In such case, we need to override the onActivityResult method that is invoked automatically when second activity returns result.


1 Answers

I think you should still use the call startActivityForResult() directly in fragment, no use getActivity().startActivityForResult().

I call the startActivityForResult() in Fragment and implement the onActivityResult in Fragment, the onActivityResult() is called correctly.

you can not call startActivityForResult() in activity, otherwise the onActivityResult() in Fragment will not be called.

like image 129
Zephyr Avatar answered Sep 18 '22 02:09

Zephyr