0

This is a follow up question to this question:

How to resume activity instead of restart when going "up" from action bar

I got 2 activities, both are defined in the manifest with android:launchMode="singleTop".

Activity A calls activity B. Activity B got a back button:

backButton.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            finish();
        }
    });

On some devices there is no problem and the previous activity resumes. Other devices are restarting the previous activity instead of resuming it. Why is that?

CodeMonkey
  • 11,196
  • 30
  • 112
  • 203

1 Answers1

0

This could be because on some devices your activity is being garbage collected to save memory. If you want to resume instead of restart even in the case of android killing your activity override the onSaveInstanceState method, and save all your variables in the bundle.

Now when you go back to your activity, if it was killed then in on create a bundle will be passed called savedINstanceState. If savedInstanceState is not null then use the data present in it to bring your activity back to the previous state.

more details here: How to use onSaveInstanceState() and onRestoreInstanceState()?

Vardaan Sharma
  • 1,125
  • 1
  • 10
  • 21
  • can I save the state in a fragment and restore it in its activity? – CodeMonkey Sep 03 '17 at 13:55
  • check out the accepted answer for this question: https://stackoverflow.com/questions/15313598/once-for-all-how-to-correctly-save-instance-state-of-fragments-in-back-stack – Vardaan Sharma Sep 03 '17 at 13:59
  • The problem is that I don't really need to restore a state, but restore the stack. When the user presses the back button in the second activity, it was after he had about 3 fragment in the first activity's stack. When Activity B finishes and A restarts, I lose the stack and I need to get back to the previous fragment but also have the other fragments on the stack in the order they were in.. how can I do that? – CodeMonkey Sep 03 '17 at 14:09
  • that might be a little more complicated. in SaveInstanceState for the activity could you also store the order of fragments in the stack? In the saveInstnaceState for the Fragment, just store the state info for that fragment and use that to recover the state. In the onCreate for the activity, use the order you had saved earlier, to keep the fragments in the existing order as well. – Vardaan Sharma Sep 03 '17 at 14:18