How to determine fragment restored from backstack

AndroidAclFragmentAndroid Support-LibraryAndroid Compatibility

Android Problem Overview


Been searching for this issue for a while to no avail now:

How to determine fragment is being restored from backstack? I'm using the compatibility library and a ListFragment inside a FragmentActivity. When an item inside ListFragment is selected, a new Fragment is started to replace the ListFragment.

I noticed that when the FragmentActivity gets paused, the Fragment's onSaveInstanceState is called. But when the Fragment is put into the back stack via FragmentTransaction, onSaveInstanceState doesn't get called, then the lifecycle methods onCreateView and onActivityCreated gets called with null savedInstanceState Bundle.

I'm asking this because I want to load some data when the Fragment is created or restored, but not so when user comes back via. backstack.

I've looked at https://stackoverflow.com/questions/7659516/how-to-check-if-fragment-was-restored-from-a-backstack but want to add more details in hopes this would incite an answer.

Edit: just noticed http://developer.android.com/reference/android/app/Fragment.html#onSaveInstanceState(android.os.Bundle) says >Note however: this method may be called at any time before onDestroy(). There are many situations where a fragment may be mostly torn down (such as when placed on the back stack with no UI showing), but its state will not be saved until its owning activity actually needs to save its state.

So onSaveInstanceState is definitely out of the question...

Android Solutions


Solution 1 - Android

I think that most simple way is do this for example in onViewCreated() method:

if (savedInstanceState == null && !mAlreadyLoaded) {
    mAlreadyLoaded = true;

    // Do this code only first time, not after rotation or reuse fragment from backstack
}

Because when android put fragment on backstack, it only destroy its view, but don't kill instance itself, so mAlreadyLoaded will be still true when fragment will be restored from backstack.

Solution 2 - Android

getSupportFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener() {	
			public void onBackStackChanged() {
				Log.i(TAG, "back stack changed ");
				int backCount = getSupportFragmentManager().getBackStackEntryCount();
				if (backCount == 0){
                                   // block where back has been pressed. since backstack is zero.
				}
			}
		});

use this addOnBackStackChangedListener.

Solution 3 - Android

When a fragment goes to back-stack onDestroyView() called. Not onDestroy().

And when a fragment pops from back-stack onCreateView() called. Not onCreate().

So add a boolean mIsRestoredFromBackstack to fragment and follow as below:

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    mIsRestoredFromBackstack = false;
}

@Override
public void onResume()
{
    super.onResume();
    if(mIsRestoredFromBackstack)
    {
        // The fragment restored from backstack, do some work here!
    }
}

@Override
public void onDestroyView()
{
    super.onDestroyView();
    mIsRestoredFromBackstack = true;
}

Solution 4 - Android

MAJOR EDIT: Oct 15 2013

The previous explanation (kept below for reference) fails when the application is put to the background and brought back to the foreground.

Instead, it is better to compare the current size of the backstack with the one when the fragment was created & put into the backstack.


Take a good look at Figure 2 in http://developer.android.com/guide/components/fragments.html#Creating

What this figure tells you is that when a fragment is restored from the backstack, its onCreate() is not called, while its onCreateView() is.


So, you may want to do something like this:

public class MyFragment extends Fragment {
    int mBackStackSize = 0;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBackStackSize = getFragmentManager().getBackStackEntryCount();
    }

    public boolean isRestoredFromBackstack() {
        return mBackStackSize > getFragmentManager().getBackStackEntryCount();
    }
}

Solution 5 - Android

If you added fragment to backstack, and after some manipulation you hide it using fragmentTransaction.hide(fragment) and then restore it from backstack like fragmentTransaction.show(fragmentManager.findFragmentByTag(fragment.getName())); you can override onHiddenChanged(boolean hidden)

@Override
public void onHiddenChanged(boolean hidden) {
	// TODO Auto-generated method stub
	super.onHiddenChanged(hidden);
	if (!hidden) {
        //fragment became visible
		//your code here
	}
}

Solution 6 - Android

In some cases you can use isVisible method to understand is it first showing of a fragment or is it restored from the backstack.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondvdView Question on Stackoverflow
Solution 1 - AndroidATomView Answer on Stackoverflow
Solution 2 - AndroidYashwanth KumarView Answer on Stackoverflow
Solution 3 - AndroidDavidView Answer on Stackoverflow
Solution 4 - AndroidGiorgos KylafasView Answer on Stackoverflow
Solution 5 - AndroidIncView Answer on Stackoverflow
Solution 6 - AndroidAlexKorovyanskyView Answer on Stackoverflow