Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 selectFrag and fired it on button click:

public void selectFrag(View view)
{    
    Fragment fr;    
 
    if(view == findViewById(R.id.showsecond)) {
        fr = new secondfragment();
    } else {
        fr = new firstfragment();
    }
         
    FragmentManager fm = getFragmentManager();
        
    FragmentTransaction ft = fm.beginTransaction();
    
    ft.replace(R.id.fragment_place,fr);
            
    ft.addToBackStack(null);
                
    ft.commit();    
}

Code works perfectly and I understand everything except addToBackStack(null).

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 null shows here. I searched on web but I only knew that it is a TAG and we could use something like this.

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

(sorry for my bad English.)

like image 585
xyz Avatar asked Sep 13 '14 09:09

xyz


1 Answers

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.

Parameters

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);
getFragmentMangager().findFragmentByTag(FRAGMENT_NAME);
like image 197
nem035 Avatar answered Nov 15 '22 16:11

nem035