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