Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restore fragment back stack with in an activity (After application is killed in background)

In an Android app-

Say I am in an Activity - MyActivity which holds one Fragment at a time.

First I loaded Fragment A to it (With no tags I added it to back stack of the FragmentManager)

Then at some point I loaded Fragment B (Again with no tags I added it to back stack of the FragmentManager)

Then at some point i loaded Fragment C (Again with no tags I added it to back stack of the FragmentManager)

I am using popBackStack() to enable back button behavior so whenever I press back from Fragment C the flow is like:

Fragment C -> Fragment B -> Fragment A -> Close MyActivity..

Everything is perfect :-)

But if I am in Fragment C and the app gets killed in background (I used "do not keep activity flag" from Settings)

and come back online Fragment C is loaded in MyActivity

but the FragmentManager's back stack contains only Fragment C..

The Back button is messing it up

Fragment C -> Close MyActivity..

Why is it so?

How to properly restore FragmentManager's back stack within an Activity?

like image 891
Arun C Avatar asked Feb 19 '16 04:02

Arun C


People also ask

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

Solution: Save required information as an instance variable in calling activity. Then pass that instance variable into your fragment.

Is fragment destroyed when activity is destroyed?

As Fragment is embedded inside an Activity, it will be killed when Activity is killed.

How do you reattach a fragment?

when your activity is recreated, the fragment gets destroyed. So you have to create new instance of fragment and add it again. Ok, but you cant retain the fragment view. If you want to retain the data which is in fragment, then use onSaveInstanceState() and onRestoreInstanceState() .

How do you save a fragment in savedInstanceState?

Here is an example: @Override protected void onCreate(Bundle savedInstanceState) { super. onCreate(savedInstanceState); if (savedInstanceState == null) { myFragment = MyFragment. newInstance(); getSupportFragmentManager() .


1 Answers

Try using alwaysRetainTaskState on your root activity. Android automatically clears the Activity backstack because it assumes that it has been a long time since you used the app and that the user wants to start again from the start.

 <activity android:alwaysRetainTaskState="true"/>

This setting will prevent that behaviour and it may follow that the behaviour is inherited by the Fragment Manager.

like image 104
shredder Avatar answered Sep 18 '22 18:09

shredder