15

I have seen this post but the solutions posted here are not working for me: get the latest fragment in backstack

When I replace a fragment for another I use:

FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction ft = manager.beginTransaction();

    ft.replace(android.R.id.tabcontent, fragment, tag);
    ft.addToBackStack(null);

    ft.commit();

So, please notice that I'm using tags to detect any fragment.

My problem in particular is the following:

Suppose I have fragment_A, fragment_B and fragment_C. I can get to fragment_C from fragment_A or fragment_B and depending of the parent of call I have to do something particular. So, again I need to recover the last FRAGMENT in the back stack.

When I try to do:

FragmentManager fm = getSupportFragmentManager();

        for(int entry = 0; entry < fm.getBackStackEntryCount(); entry++){
            String ide = fm.getBackStackEntryAt(entry).getName();
           Log.i("TAG", "Found fragment: " + ide);
        }

I get nulls. If I use getId() instead, I get numbers so I tried doing:

int id = fm.getBackStackEntryAt(entry).getId();
Fragment fragment = fm.findFragmentById(id);
Log.i("TAG", "Found fragment: " + fragment.getTag());

But I get nulls.. I dont know what else to do, so any help will be appreciated.

Edit: I call this methods in onBackPressed() { ...}

Community
  • 1
  • 1
kiduxa
  • 3,339
  • 11
  • 37
  • 52

1 Answers1

16

If you're using BackStackEntry.getName(), it should be:

ft.replace(android.R.id.tabcontent, fragment, tag);
ft.addToBackStack(tag);
Paul Burke
  • 25,496
  • 9
  • 66
  • 62
  • bad practice to use same tag for the fragment that is supposed to be added or replace with. and the backstack which is actually should be the name of the previous fragment to remember the transaction is related to that fragment. – eC Droid Aug 08 '17 at 14:21