Android Recovering the order of fragments in the stack

I have 2 actions, A and B. Each action is a container for fragments that are replaced with a FragmentTransaction .

I had a problem on some devices, when the user opens Activity B when he was in Activity A, the first action is probably destroyed, which means that when the user clicks the back button, he makes the first action recreated, a normal device, it will just resume.

My main problem is that the user loses his stack of fragments, which he had in the first action. When the user opened the 2nd operation, he was already 3 fragments of the "deep" first activity. How to restore the stack and return the user to the moment when it was destroyed?

+5
source share
1 answer

This should run Android OS automatically. You can enable the “do not continue” developer option to always simulate this behavior (destroying your activity) when your activity goes to the background. After that you can start debugging. Some things to check:

  • In onCreate activity do you call super onCreate with saveInstanceState?

  • If you set a breakpoint at the beginning of onCreate when you “come back” into action, is there a state of the saved instance?

  • Where do you create fragments? Do you recreate them manually (you shouldn't)?

  • Are your fragments hardcoded in the layout or replaced in the layout (replacing the container view)?

* EDIT *

From your answer, I get that this is a problem, you say: "At the end of onCreate, I replace the fragment with the fragment transaction and thus load the first application fragment" =>, you should not do this when the saved InstanceState is not null. Otherwise, you destroy what already exists from the saved state.

Check here: https://developer.android.com/training/basics/fragments/fragment-ui.html

Note the return when savedInstanceState does not matter.

 public class MainActivity extends FragmentActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.news_articles); // Check that the activity is using the layout version with // the fragment_container FrameLayout if (findViewById(R.id.fragment_container) != null) { // However, if we're being restored from a previous state, // then we don't need to do anything and should return or else // we could end up with overlapping fragments. if (savedInstanceState != null) { return; } // Create a new Fragment to be placed in the activity layout HeadlinesFragment firstFragment = new HeadlinesFragment(); // In case this activity was started with special instructions from an // Intent, pass the Intent extras to the fragment as arguments firstFragment.setArguments(getIntent().getExtras()); // Add the fragment to the 'fragment_container' FrameLayout getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container, firstFragment).commit(); } } } 
+1
source

Source: https://habr.com/ru/post/1271486/


All Articles