116

I have a customer code. There is only one activity for all of the fragments i.e. the single activity is managing all the fragments.

This activity contains the following code for any fragment at the method end of that fragment-

For example - fragment MoreFragment:

MoreFragment firstFragment = new MoreFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.article_fragment, firstFragment)
.addToBackStack(null).commit();

So,

1) What is the meaning of addToBackStack(null) followed by a commit() ?

2) Why you need to pass a null parameter to addToBackStack ?

3) How to get that fragment after being added like this ?

Seems like this code is useless as I ran the code without the last line .addToBackStack(null).commit() and it ran without any problems.

sjain
  • 23,126
  • 28
  • 107
  • 185
  • http://developer.android.com/reference/android/app/FragmentTransaction.html#addToBackStack(java.lang.String) in some cases you must call that method. – Lucifer Apr 10 '14 at 10:10
  • http://stackoverflow.com/a/18846336/3330969 – Lucifer Apr 10 '14 at 10:15
  • 3
    You can pass the fragment name as the parameter to addToBackStack(name) instead of Null. If you pass Null then you would not be able to use the method FragmentManager.popBackStackImmediate(String name, int flags); or popBackStack(String name, int flags); because the name was Null. So the popBackstack methods will not work. I suggest you pass the Fragment name as the parameters instead of passing null. – luckylukein May 26 '16 at 18:42
  • It's the name of the transaction. Doesn't need a name to pop the back stack and reverse the transactions. – the_prole Mar 15 '22 at 21:07

3 Answers3

124

What is the meaning of addToBackStack(null) followed by a commit()?

Quoting docs:

By calling addToBackStack(), the replace transaction is saved to the back stack so the user can reverse the transaction and bring back the previous fragment by pressing the Back button.

If you add multiple changes to the transaction (such as another add() or remove()) and call addToBackStack(), then all changes applied before you call commit() are added to the back stack as a single transaction and the Back button will reverse them all together.

The order in which you add changes to a FragmentTransaction doesn't matter, except:

You must call commit() last. If you're adding multiple fragments to the same container, then the order in which you add them determines the order they appear in the view hierarchy.

So you have to commit at the last.

Why you need to pass a null parameter to addToBackStack?

It don't need to be null, it can be a string. If you don't want, just pass null.

public abstract FragmentTransaction addToBackStack (String name)

Added in API level 11 Add this transaction to the back stack. This means that the transaction will be remembered after it is committed, and will reverse its operation when later popped off the stack.

Parameters name An optional name for this back stack state, or null.

Concerning:

Seems like this code is useless as I ran the code without the last line .addToBackStack(null).commit() and it ran without any problems

If you want to navigate to previous fragment add it to backstack. So it depends on whether you want to add the fragment to the backstack.

How to get that fragment after being added like this?

You already have the fragment instance firstFragment. So I don't know what you mean by get the fragment later.

More information @

http://developer.android.com/guide/components/fragments.html

http://developer.android.com/reference/android/app/FragmentTransaction.html#addToBackStack(java.lang.String)

Felipe
  • 150
  • 1
  • 16
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • You can also add this to your answer from the API doc: Add this transaction to the back stack. This means that the transaction will be remembered after it is committed, and will reverse its operation when later popped off the stack. Parameters name An optional name for this back stack state, or null. – Dyrborg Apr 10 '14 at 10:16
  • So as I understood, the whole purpose of adding to backstack is to perform navigation as we do with back button to go to previous fragment ? – sjain Apr 10 '14 at 10:24
  • ok so if you are passing a parameter to addToBackStack then why we need to do `getFragmentManager().popBackStackImmediate()` if back button can do it just on its own with/without parameter pass ? See the answer of - http://stackoverflow.com/questions/21156153/popbackstack-after-addtobackstack-does-not-work – sjain Apr 10 '14 at 10:32
  • @VedPrakash you need not have. Also that's a differen question and answer altogether. You can easily find out yourself by having two fragments adding them to back stack and pressing back button – Raghunandan Apr 10 '14 at 10:34
  • @VedPrakash read managing fragments @ http://developer.android.com/guide/components/fragments.html – Raghunandan Apr 10 '14 at 10:37
  • 1
    when using `String name` is "useful" then? – M.kazem Akhgary Oct 26 '18 at 08:13
  • @M.kazemAkhgary i din't understand. its just a string param. – Raghunandan Oct 26 '18 at 10:04
26

The tag string in addToBackStack(String name) gives a way to locate the back stack for later pop directly to that location. It meant to be used in the method popToBackStack(String name, int flags):

Pop the last fragment transition from the manager's fragment back stack. This function is asynchronous -- it enqueues the request to pop, but the action will not be performed until the application returns to its event loop.

name: If non-null, this is the name of a previous back state to look for; if found, all states up to that state will be popped. The POP_BACK_STACK_INCLUSIVE flag can be used to control whether the named state itself is popped. If null, only the top state is popped.

flags: Either 0 or POP_BACK_STACK_INCLUSIVE.

In other words, it will pop your back stack until it finds the fragment that was added by the name in addToBackStack(String name).

For example, if you do a series of additions or replaces to the fragment manager giving the names "frag1", "frag2", "frag3", "frag4" and later want to go back directly to the fragment 2 added with addToBackStack("frag2"), you call popToBackStack("frag2", 0).

So,

  • Use .addToBackStack("fragName"): if you want later popToBackStack(String name, int flags) to pop more than one back stack.

  • Use .addToBackStack(null): If you don't want later pop more than one back stack, but still want to pop one at a time. Do this even if you won't explicitly call popToBackStack() but instead will let the back press default implementation handle the back stack.

  • Use .disallowAddToBackStack(): If you don't want either the back press or call popBackStack() it explicitly. It will make sure no part of the code is using .addToBackStack().

Allan Veloso
  • 5,823
  • 1
  • 38
  • 36
2

Your answers are deprecated. If you don't want to add fragments to back stack, you should use below snippet of code:

    public static void replaceFragment (@NonNull FragmentManager fragmentManager,
            @NonNull Fragment fragment, int frameId){

        checkNotNull(fragmentManager);
        checkNotNull(fragment);
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(frameId, fragment);
        transaction.disallowAddToBackStack(); // <-- This makes magic!
        transaction.commit();
    }

Below you have cute example of how use it:

GameFragment fragment = GameFragment.newInstance(mGameObject, currentQuestion);
ActivityUtils.replaceFragment(getFragmentManager(), fragment, R.id.main);
Felipe
  • 150
  • 1
  • 16
Eliasz Kubala
  • 3,836
  • 1
  • 23
  • 28
  • 6
    Deprecated where? I don't see anything in the documentation or the FragmentTransaction source. – Rup Apr 24 '17 at 13:27
  • 3
    Beware, if you `disallowAddToBackStack`, then _Any future calls to addToBackStack will throw IllegalStateException. If addToBackStack has already been called, this method will throw IllegalStateException._ – Kathir Feb 07 '19 at 17:38