Search code examples
androidonactivityresult

getSupportFragmentManager().getFragments() NPE


I tried to post the Activity's onActivityResult() to its sub-Fragments and got a NPE. I have no idea why the fragment is null.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    for (Fragment fragment : getSupportFragmentManager().getFragments()) {
        if (fragment != null) {
            fragment.onActivityResult(requestCode, resultCode, data);
        }
    }
}

Excpetion:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.Fragment.onActivityResult(int, int, android.content.Intent)' on a null object reference


Solution

  • There is a method "makeInactive(Fragment f)" in FragmentManager which use "mActive.set(f.mIndex, null);" to set the fragment null. I should have thought it just remove the fragment from the list instead of setting a null to it.