How can I maintain fragment state when added to the back stack?

160,841

Solution 1

If you return to a fragment from the back stack it does not re-create the fragment but re-uses the same instance and starts with onCreateView() in the fragment lifecycle, see Fragment lifecycle.

So if you want to store state you should use instance variables and not rely on onSaveInstanceState().

Solution 2

Comparing to Apple's UINavigationController and UIViewController, Google does not do well in Android software architecture. And Android's document about Fragment does not help much.

When you enter FragmentB from FragmentA, the existing FragmentA instance is not destroyed. When you press Back in FragmentB and return to FragmentA, we don't create a new FragmentA instance. The existing FragmentA instance's onCreateView() will be called.

The key thing is we should not inflate view again in FragmentA's onCreateView(), because we are using the existing FragmentA's instance. We need to save and reuse the rootView.

The following code works well. It does not only keep fragment state, but also reduces the RAM and CPU load (because we only inflate layout if necessary). I can't believe Google's sample code and document never mention it but always inflate layout.

Version 1(Don't use version 1. Use version 2)

public class FragmentA extends Fragment {
    View _rootView;
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        if (_rootView == null) {
            // Inflate the layout for this fragment
            _rootView = inflater.inflate(R.layout.fragment_a, container, false);
            // Find and setup subviews
            _listView = (ListView)_rootView.findViewById(R.id.listView);
            ...
        } else {
            // Do not inflate the layout again.
            // The returned View of onCreateView will be added into the fragment.
            // However it is not allowed to be added twice even if the parent is same.
            // So we must remove _rootView from the existing parent view group
            // (it will be added back).
            ((ViewGroup)_rootView.getParent()).removeView(_rootView);
        }
        return _rootView;
    }
}

------Update on May 3 2005:-------

As the comments mentioned, sometimes _rootView.getParent() is null in onCreateView, which causes the crash. Version 2 removes _rootView in onDestroyView(), as dell116 suggested. Tested on Android 4.0.3, 4.4.4, 5.1.0.

Version 2

public class FragmentA extends Fragment {
    View _rootView;
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        if (_rootView == null) {
            // Inflate the layout for this fragment
            _rootView = inflater.inflate(R.layout.fragment_a, container, false);
            // Find and setup subviews
            _listView = (ListView)_rootView.findViewById(R.id.listView);
            ...
        } else {
            // Do not inflate the layout again.
            // The returned View of onCreateView will be added into the fragment.
            // However it is not allowed to be added twice even if the parent is same.
            // So we must remove _rootView from the existing parent view group
            // in onDestroyView() (it will be added back).
        }
        return _rootView;
    }

    @Override
    public void onDestroyView() {
        if (_rootView.getParent() != null) {
            ((ViewGroup)_rootView.getParent()).removeView(_rootView);
        }
        super.onDestroyView();
    }
}

WARNING!!!

This is a HACK! Though I am using it in my app, you need to test and read comments carefully.

Solution 3

I guess there is an alternative way to achieve what you are looking for. I don't say its a complete solution but it served the purpose in my case.

What I did is instead of replacing the fragment I just added target fragment. So basically you will be going to use add() method instead replace().

What else I did. I hide my current fragment and also add it to backstack.

Hence it overlaps new fragment over the current fragment without destroying its view.(check that its onDestroyView() method is not being called. Plus adding it to backstate gives me the advantage of resuming the fragment.

Here is the code :

Fragment fragment=new DestinationFragment();
FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction ft=fragmentManager.beginTransaction();
ft.add(R.id.content_frame, fragment);
ft.hide(SourceFragment.this);
ft.addToBackStack(SourceFragment.class.getName());
ft.commit();

AFAIK System only calls onCreateView() if the view is destroyed or not created. But here we have saved the view by not removing it from memory. So it will not create a new view.

And when you get back from Destination Fragment it will pop the last FragmentTransaction removing top fragment which will make the topmost(SourceFragment's) view to appear over the screen.

COMMENT: As I said it is not a complete solution as it doesn't remove the view of Source fragment and hence occupying more memory than usual. But still, serve the purpose. Also, we are using a totally different mechanism of hiding view instead of replacing it which is non traditional.

So it's not really for how you maintain the state, but for how you maintain the view.

Solution 4

I would suggest a very simple solution.

Take the View reference variable and set view in OnCreateView. Check if view already exists in this variable, then return same view.

   private View fragmentView;

   public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        if (fragmentView != null) {
            return fragmentView;
        }
        View view = inflater.inflate(R.layout.yourfragment, container, false);
        fragmentView = view;
        return view;
    }

Solution 5

I came across this problem in a Fragment containing a map, which has too many setup details to save/reload. My solution was to basically keep this Fragment active the whole time (similar to what @kaushal mentioned).

Say you have current Fragment A and wants to display Fragment B. Summarizing the consequences:

  • replace() - remove Fragment A and replace it with Fragment B. Fragment A will be recreated once brought to the front again
  • add() - (create and) add a Fragment B and it overlap Fragment A, which is still active in the background
  • remove() - can be used to remove Fragment B and return to A. Fragment B will be recreated when called later on

Hence, if you want to keep both Fragments "saved", just toggle them using hide()/show().

Pros: easy and simple method to keep multiple Fragments running
Cons: you use a lot more memory to keep all of them running. May run into problems, e.g. displaying many large bitmaps

Share:
160,841

Related videos on Youtube

Eric
Author by

Eric

Updated on September 22, 2021

Comments

  • Eric
    Eric almost 3 years

    I've written up a dummy activity that switches between two fragments. When you go from FragmentA to FragmentB, FragmentA gets added to the back stack. However, when I return to FragmentA (by pressing back), a totally new FragmentA is created and the state it was in is lost. I get the feeling I'm after the same thing as this question, but I've included a complete code sample to help root out the issue:

    public class FooActivity extends Activity {
      @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(android.R.id.content, new FragmentA());
        transaction.commit();
      }
    
      public void nextFragment() {
        final FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(android.R.id.content, new FragmentB());
        transaction.addToBackStack(null);
        transaction.commit();
      }
    
      public static class FragmentA extends Fragment {
        @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
          final View main = inflater.inflate(R.layout.main, container, false);
          main.findViewById(R.id.next_fragment_button).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
              ((FooActivity) getActivity()).nextFragment();
            }
          });
          return main;
        }
    
        @Override public void onSaveInstanceState(Bundle outState) {
          super.onSaveInstanceState(outState);
          // Save some state!
        }
      }
    
      public static class FragmentB extends Fragment {
        @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
          return inflater.inflate(R.layout.b, container, false);
        }
      }
    }
    

    With some log messages added:

    07-05 14:28:59.722 D/OMG     ( 1260): FooActivity.onCreate
    07-05 14:28:59.742 D/OMG     ( 1260): FragmentA.onCreateView
    07-05 14:28:59.742 D/OMG     ( 1260): FooActivity.onResume
    <Tap Button on FragmentA>
    07-05 14:29:12.842 D/OMG     ( 1260): FooActivity.nextFragment
    07-05 14:29:12.852 D/OMG     ( 1260): FragmentB.onCreateView
    <Tap 'Back'>
    07-05 14:29:16.792 D/OMG     ( 1260): FragmentA.onCreateView
    

    It's never calling FragmentA.onSaveInstanceState and it creates a new FragmentA when you hit back. However, if I'm on FragmentA and I lock the screen, FragmentA.onSaveInstanceState does get called. So weird...am I wrong in expecting a fragment added to the back stack to not need re-creation? Here's what the docs say:

    Whereas, if you do call addToBackStack() when removing a fragment, then the fragment is stopped and will be resumed if the user navigates back.

    • Jan-Henk
      Jan-Henk about 12 years
      Does the onCreate() method of the fragment get called again after going back to it? If I remember correctly this should not be the case. If this is not the case, you can just save state in instance variables.
    • Jake Wharton
      Jake Wharton about 12 years
      @Jan-Henk What about things that have to be fetched? For instance, the scroll position of a ListView. Seems like far too much hoop-jumping to attach a scroll listener and update an instance variable.
    • Jan-Henk
      Jan-Henk about 12 years
      @JakeWharton I agree it should be easier, but as far as I know there is no way around this because onCreateView is called when a fragment is restored from the backstack. But I could be wrong :)
    • Eric
      Eric about 12 years
      onCreate does not get called. So apparently it's re-using the same instance but calling onCreateView again? Lame. I guess I can just cache the result of onCreateView and just return the existing view if onCreateView gets called again.
    • Eric
      Eric about 12 years
      Yup, that works. @Jan-Henk if you want to submit an answer I'll mark it as accepted.
    • LoveMeSomeFood
      LoveMeSomeFood over 10 years
      Exactly what I was looking for hours. Can you post how you achieved this using instance variable?
    • Muhammad Babar
      Muhammad Babar over 10 years
      hide() and add() instead of replace() will be a good solution though!
    • Rule
      Rule almost 9 years
      How do you go back to the first fragment with the back button if you didn't override the activity's onBackPressed() method?
    • frostymarvelous
      frostymarvelous over 8 years
      So I recently started my own implementation in github.com/frostymarvelous/Folio and came across a problem. I'm able to create about 5 complex Pages/Fragments before I start getting OOM crashes. That's what led me here. Hiding and Showing is simply not enough. Views are too memory heavy.
  • Colin M.
    Colin M. over 11 years
    The current version of the documentation contradicts this claim. The flowchart says what you state, but the text in the main area of the page says onCreateView() is only called the first time the Fragment is displayed: developer.android.com/guide/components/fragments.html I'm fighting this issue now, and I don't see any methods called when returning a fragment from the backstack. (Android 4.2)
  • princepiero
    princepiero almost 11 years
    Tried to logged its behavior. The onCreateView() is always called when the fragment is being displayed.
  • LoveMeSomeFood
    LoveMeSomeFood over 10 years
    In my case, by adding a fragment instead of replacing causes problem when using polling or anyother kind of web request is used in the fragment. I want to pause this polling in Fragment A when Fragment B is added. Any idea on this?
  • kaushal trivedi
    kaushal trivedi over 10 years
    How you are using polling in FirstFragment ? You have to do that manually as both of the fragments remain in memory.So you can use their instances to perform necessary action.Thats the clue,generate an event in main activity which do something when you add second fragment. Hope this will help.
  • LoveMeSomeFood
    LoveMeSomeFood over 10 years
    Thank you for the clue =). I have this done. But is this the only way to do it? And an appropriate way? Also When I press home button and launch application again all fragments get active again. Suppose Im here in Fragment B through this way. Activity A{Fragment A --> Fragment B} when I launch the application again after pressing home button both fragment's onResume() is called and hence they start their polling. How can I control this?
  • kaushal trivedi
    kaushal trivedi over 10 years
    Unfortunately you can not,System doesn't work in normal behaviour in this way,it will consider both fragment as direct child of activity.Though it served the purpose of maintaining the fragment state,other normal things get very hard to manage.Lately i discovered all this issues,now my suggestion is to not go for this way.sorry.
  • LoveMeSomeFood
    LoveMeSomeFood over 10 years
    NP.Thank you for the help!
  • LoveMeSomeFood
    LoveMeSomeFood over 10 years
    Also adding too many fragments, lets say 10 for example (hiding the previous) without replacing will that cause memory issues?
  • kaushal trivedi
    kaushal trivedi over 10 years
    Of course,in last i will say not to go with this approach until you find any other solution.Because it is hard to manage.
  • LoveMeSomeFood
    LoveMeSomeFood over 10 years
    OK.. Thank you so much!!
  • Otuyh
    Otuyh over 10 years
    This explained so much to me! Thanks a lot!
  • blizzard
    blizzard about 10 years
    @ColinM. Any solution for the problem?
  • ovluca
    ovluca about 10 years
    nice answer... Thank you my friend.
  • Tooroop
    Tooroop about 10 years
    This is the real answer! Thanks
  • Achin Kumar
    Achin Kumar about 10 years
    Excellent answer. Though I didn't quite absorb what all happened. I would appreciate if you could point to any detailed documentation related to this. Thanks
  • Nilzor
    Nilzor almost 10 years
    What if that fragment contains a WebView? The WebView relies on restoreInstanceState() in order to restore its state. This is a mess. Is this the solution? stackoverflow.com/a/17869748/507339
  • Kartik_Koro
    Kartik_Koro almost 10 years
    This works great for me, why is this not the accepted answer?
  • SunGa
    SunGa almost 10 years
    This worked for me. Excellent wayout for addressing the issue!
  • Christian Brüggemann
    Christian Brüggemann almost 10 years
    I tried it out and ran into a huge issue. It seems the fragment is not correctly attached to the activity in this case, or at least its views are not. Even getActivity() returns null.
  • Don Rhummy
    Don Rhummy over 9 years
    This doesn't work for me. My instance variables are null on returning to the fragment! How can I save the state?
  • traninho
    traninho over 9 years
    Holding a reference to whole fragment's rootview is a bad idea IMO. If you are continuously adding several fragments to a backstack and all of them are holding its rootview (which has a quite big memory footprint), then there is high possibility you end up with the OutOfMemoryError since all of the fragments holds rootview reference and GC cant collect it. I think the better approach is to inflate the view all the time (and let Android system handle its view creation/destroying) and onActivityCreated/onViewCreated check if your data is null. If yes, then load it, else set the data to views.
  • Kong Ken
    Kong Ken over 9 years
    This is the best answer. Cheers!
  • traninho
    traninho over 9 years
    @gZerone I think that Vince Yuan's approach can be successfuly used if you are sure that you will have limited count of fragments in a backstack (for example max 5). But in my case, I have a movie detail fragment which also contains "recommended movies" grid. If user clicks on a recommended movie then a new movie detail fragment is created and showed. So if I use this approach, then I can easily reach OOME as there will be a lot of movie detail fragments in the backstack.
  • Krylez
    Krylez over 9 years
    Don't do this! When the Fragment's view hierarchy is created, it contains an internal reference to the Activity that held the fragment at the time. When a configuration change occurs, the Activity is often re-created. Re-using the old layout keeps that zombie Activity around in memory along with whatever objects it also references. Wasting memory like this hinders performance and makes your app a top candidate for immediate termination when not in the foreground.
  • roger
    roger over 9 years
    In my situation, _rootView.getParent() just return null, because _rootView is just my rootview.
  • AllDayAmazing
    AllDayAmazing over 9 years
    @traninho I asked this in the linked similar question, but wouldn't setting any View as an instance variable cause the bad effects you are describing? Almost every example I have seen does this, and any View holds references to is parent, so what is the difference here?
  • traninho
    traninho over 9 years
    @AllDayAmazing This is a good point. To be honest, I am very confused right now. Can anybody try to explain why holding a reference to a fragment's rootview is not ok but holding a reference only for any child of rootview (which has a reference to rootview anyway) is ok?
  • dell116
    dell116 about 9 years
    STAY AWAY FROM THIS unless you want to waste 5 hours finding out what's bugging out your code.....then only to find that this is the cause. Now I have to refactor a bunch of stuff because I used this hack. It's much better to use fragmentTransaction.add if you want to keep the fragment's UI in-tact when bringing another into view (even on top). fragmentTransaction.replace() is meant to destroy the fragment's views.....don't fight the system.
  • dell116
    dell116 about 9 years
    Vince, you should seriously just tell others not to use this answer anymore. Even after using the logical paths I suggested, this hack will cause fragments to stay in the FragmentManager after calling FragmentTransaction.remove(hackedFragment) because the inflated viewgroup you're keeping in memory prevents the fragment from being removed (seriously dangerous memory leak). I can confirm this only on API level 22, but I'd down-vote this answer 10 times (killing my own reputation) if I could. Just use FragmentTransaction.add() to keep any previously viewed fragment's view hierarchy in-tact.
  • Vince Yuan
    Vince Yuan about 9 years
    @dell116 Thanks for the comment. But I don't understand it causes memory leak. After calling FragmentTransaction.remove(hackedFragment), hackedFragment's refCount -1, and hackedFragment's member varaibles' refCount -1. Java GC should handle it correctly.
  • dell116
    dell116 about 9 years
    @VinceYuan - I tested with the latest v7-appcompat library on Android 5.1 and this left 6 instances of a fragment that should have been removed in my activity's FragmentManager. Even if the GC will handle it correctly (which I don't believe it will) this is causing unnecessary strain on memory for your app as well as the device in general. Simply using .add() completely removes the need for all of this hacky code. Doing this is completely against what using FragmentTransaction.replace() was meant to do in the first place.
  • nickmartens1980
    nickmartens1980 almost 9 years
    The GC will handle it correctly if no more references exist. But it is up to the developer to clear those. This makes this approach extremely difficult to implement and I will advise against it all the time. Very bad approach. I also don't like the suggestion that Apple has done a better job with this than Google has. Managing fragments is difficult if you don't know how it works. Using other platform approaches (if that is the case) is definitely not helping. Developing for Android requires you to think different.
  • n j
    n j over 8 years
    Thanks for this, I knew i was missing something, Thanks again.
  • agrosner
    agrosner over 8 years
    Probably the worst idea I've ever seen. If you are having issues with how fast your layout is rendered, you have other issues going on here...You will leak Activity for every screen rotation if the Fragment is retained.
  • Admin
    Admin over 8 years
    1method( Attempt to invoke virtual method 'void android.view.ViewGroup.removeView(android.view.View)' on a null object reference) and 2 method is wrong, I get java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position, its a good try, but not works correctly
  • IcyFlame
    IcyFlame about 8 years
    This is probably not a good idea. onCreateView called sparingly, and only when actually the view is required. Hence, the general idea with the platform is that if the platform calls onCreateXXX CREATE it!.
  • Mahdi
    Mahdi almost 8 years
    so if we should not relay on save instance how should save fragment status and data?
  • Google
    Google over 7 years
    can you please tell me when we remove fragment b and return to A then which method is called in Fragment A ? i want to take some action when we remove the fragment B.
  • Krzysztof Dubrowski
    Krzysztof Dubrowski about 7 years
    This is absolutely wrong as the onCreateView needs to inflate/create the view in a lot of different situations for example a configuration change. The actual solution to keeping the state of your data is to actually save it in onSaveInstanceState calls and retrieve them through savedInstanceState bundles
  • zafrani
    zafrani over 6 years
    Another issue that no one has mentioned is transition effects. If you use an animation like sliding a fragment in, during the duration of the animation the rootView has a parent but that parent DOES NOT have the rootView as a child. Trying to remove rootView from the parent will not work. If the user pushes back in the middle of the animation your app will crash with an IllegalStateException.
  • Marcel Bro
    Marcel Bro over 6 years
    onSaveInstanceState() is also called when the system destroys Activity because it lacks resources.
  • Machavity
    Machavity over 6 years
    Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you've made.
  • Daksh Gargas
    Daksh Gargas about 6 years
    what instance variables are we talking about here?
  • filthy_wizard
    filthy_wizard about 5 years
    im returning from navigation components backstack. using navigateUp(). onViewCreated is called. i save the position in onViewDestroyed in arguments. onViewCreated called on pop and attempted scroll to previous position has no effect.??
  • Rohit Sharma
    Rohit Sharma over 4 years
    Perfect Answer. Thanks :)
  • Fugogugo
    Fugogugo over 4 years
    can someone explain this in code? I am confused with the term instance variable here
  • Arun P M
    Arun P M about 4 years
    There is a chance of memory leak if we didn't remove 'fragmentView' variable in onDestroy()
  • Mehmet Gür
    Mehmet Gür about 4 years
    @ArunPM so how to remove fragmentView in onDestroy() ? if (_rootView.getParent() != null) { ((ViewGroup)_rootView.getParent()).removeView(_rootView); } is appropriate to clear memory ?
  • Mehmet Gür
    Mehmet Gür about 4 years
    @Mandeep Singh I'm using your solution because it's really very simple. But please can you tell me this is reliable solution ? Have you ever face a problem with using this way ? Thanks.
  • Mandeep Singh
    Mandeep Singh about 4 years
    @MehmetGür i am using this solution many time. Till now i did not get any memory leak error. But you can use ArunPM solution with that if you want. I think he is telling to set fragmentView to null in OnDestroy() Method.
  • Arun P M
    Arun P M about 4 years
    I'm using LeakCanary for detecting memory leaks and its throwing leak issues when I followed this method. But as @Mandeep Sigh mentioned in the comment we can overcome this issue by assigning null to fragmentView variable in onDestroy() method.
  • Arun P M
    Arun P M about 4 years
    As per my knowledge, when a fragment getting destroys, the view associated with the fragment is cleared in onDestroyView(). This clearing is not happening for our backup view variable (here fragmentView ) and it will cause memory leak when the fragment back stacked/destroyed. You can find the same reference in [Common causes for memory leaks] (square.github.io/leakcanary/fundamentals/…) in LeakCanery introduction.
  • Mehmet Gür
    Mehmet Gür about 4 years
    @MandeepSingh @Arun P M thanks for answers! I used this way in onDestroy(): if (view.getParent() != null) { ((ViewGroup)view.getParent()).removeView(view); }
  • Mehmet Gür
    Mehmet Gür about 4 years
    Is My way true or I must this: view=null ? And also I'm not sure using this in onDestroy() instead of onDestroyView(). I couldn't understand which method more appropriate for this situation. @Arun PM
  • Arun P M
    Arun P M about 4 years
    Hi @MehmetGür, the leaking mainly happens when you put your fragment into the back stack. You can simply null out your view references like onDestroy(){fragmentView = null }. Please check this stack overflow answer for some more insights.