androidandroid-nested-fragment

Android nested fragments -- how to call onActivityResult() for just one child fragment


I have a parent fragment and in that there are three nested child fragments. I want to call the onActivityResult() on my child fragment.

I am aware that for nested fragments onActivityResult() is not called, so we need to explicitly call it from the parent fragment.

So In my parent fragment I have overridden the onActivityResult:-

@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    List<Fragment> fragments = getChildFragmentManager().getFragments();
    if (fragments != null) {
        for (Fragment fragment : fragments) {
                fragment.onActivityResult(requestCode, resultCode, intent);
        }
    }
} 

But the issue is, even when I am working on just one child fragment, the onActivityResult() gets called for all the three nested fragments.

From each of the child fragment I am launching system activity(contact picker) and where I cannot set and intent extra, it returns null (system activities will not send back the extras with which they're called). So is there a way to identify a particular child fragment and just run the onActivityResult() for the nested fragment, for which I click the button. Following is the code in my nested fragment.

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    contactPickerButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent contactPickerIntent = new Intent(ACTION_GET_CONTENT);
            contactPickerIntent.setType(CONTENT_ITEM_TYPE);
            getParentFragment().startActivityForResult(contactPickerIntent, PICK_CONTACT_REQUEST_ID);
        }
    });
}

Solution

  • Fragments are anyhow active. In that case, you can just store the nested fragment id in your onActivityCreated() method as:

    FRAGMENT_ID=((RelativeLayout)view.getParent()).getId(); // cast it to your parent view
    

    and then you can check the same in onActivityResult of nested fragment.Something like this

     @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if ((requestCode == REQUEST_ID) && 
                (resultCode == RESULT_OK) &&
                (getId() == FRAGMENT_ID)) {
                // your logic here
            }
        }
    

    There can be a better way, but this will surely work. Hope this helps.