xyz xyz - 1 year ago 133
Android Question

What is the purpose of null in addToBackStack(null)?

I am new to Andoid development and I have created a snippet for replacing fragments programetically.

I followed the guide on android developers.

I have create a method named

and fired it on button click:

public void selectFrag(View view)
Fragment fr;

if(view == findViewById( {
fr = new secondfragment();
} else {
fr = new firstfragment();

FragmentManager fm = getFragmentManager();

FragmentTransaction ft = fm.beginTransaction();




Code works perfectly and I understand everything except

I experimented and understood that this method is for adding the fragment to the back button's stack, so that if we click back button, it do not leave the screen and show the previous work.

But, I do not understand what
shows here. I searched on web but I only knew that it is a
and we could use something like this.

So, my question is very simple :What is meant by null here? or What do null does?

(sorry for my bad English.)

Answer Source

From documentation, it is pretty clear:

public abstract FragmentTransaction addToBackStack (String name)

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.


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

So your parameter is optional and represents the name of the fragment.

If you just want to add this transaction to the back stack and don't need to access it later then you can put null as the name.

In this context, null in plain English means "I don't need a name for this fragment". That is why it says the name is optional. If you do put a name you can use that name later. If you put a null that just means "add this fragment to the back stack and I don't need it anymore".

The use of the name is to identify that specific fragment. This can be useful for example if you want to obtain that fragment from the FragmentManager:

addToBackStack (FRAGMENT_NAME);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download