onActivityResult For Fragment

Nath5 picture Nath5 · Nov 18, 2013 · Viewed 58k times · Source

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.

Answer

Zephyr picture Zephyr · Jan 26, 2014

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.