0

I have an Activity with have a different stack of fragments. One fragment, which has a list of items, starts an activity of detail. In this activity I need the fragment instance to do something (related to dagger 2) when the activity is created.

I have tried the findFragmentById and findFragmentByTag methods but returns null.

I have this code in my activity:

protected void initDI() {
    ContactsFragment contactsFragment = (ContactsFragment) getSupportFragmentManager().findFragmentById(fragmentId);
    ContactsFragmentComponent fragmentComponent = contactsFragment.getFragmentComponent();
    DetailContactActivityComponent subcomponent = fragmentComponent.createSubcomponent(new DetailContactActivityModule());
    subcomponent.injectDetailContactActivity(this);
}

How can I get the instance of the fragment in the activity?

EDIT:

The problem is when I start a new activity and I get the getFragmentManager instance, this instance is different from the fragmentManager of the fragment that starts the activity.

beni
  • 3,019
  • 5
  • 35
  • 55
  • check this question out http://stackoverflow.com/questions/8482606/when-a-fragment-is-replaced-and-put-in-the-back-stack-or-removed-does-it-stay – karan Nov 05 '15 at 10:51

1 Answers1

0

If you could not find them this way, then try to look through all backstack fragments:

    boolean foundMyFragment = false;
        String fragmentBackstackTag = "";
        FragmentManager fm = getSupportFragmentManager();
        for(int entry = 0; entry < fm.getBackStackEntryCount(); entry++){
            fragmentBackstackTag = fm.getBackStackEntryAt(entry).getName();
            Log.i(TAG, "Found fragment: " + fragmentBackstackTag);

            // check if null, because sometimes fragmentBackstacktag is null
            if (fragmentBackstackTag != null) {
                if (fragmentBackstackTag.equals("fragmentTagYouAreSearching")) {
                    foundMyFragment = true;
                    // get fragment from backstack
                }
            }
        }
Filip Luchianenco
  • 6,912
  • 9
  • 41
  • 63