Android activity navigation save state

android, android-fragments, navigation, state

Solution

Lets try this:

In the intent of the parentActivity(if you can set it before you create parentActivity its best, otherwise you may have to use setIntent):

    currentActivityIntent.putExtra("random-unique-key-for-each-activity",
random-unique-key-for-each-activity);

And before you create a child activity, u put following in a map:

myKeyIntentMap.put(random-unique-key-for-each-activity, currentActivityIntent);

In the method triggered on "Up" event :

{
String parentKey = currentActivity.parentActivity.getIntent.getStringExtra("random-unique-key-for-each-activity");
Intent intentToLaunch = (Intent)myKeyIntentMap.get(parentKey);
intentToLaunch.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP );
startActivity(intentToLaunch);
}

This way, using the intent, even if your History Stack is A-someAct1-someAct2-B, and u launch intent resolving to A, it will be "brought to front" killing someActs.

P.S. I havent done any null checks and havent kept in mind the exact method names, just given you an approach.

Problem

In the main activity `ActivityA` I replace `FragmentA` by fragment `FragmentB`. From `FragmentB` the user can start a new activity `ActivityB`. By hitting the back button in `ActivityB`, `ActivityA` is displayed showing `FragmentA`. I was expecting to see `FragmentB` with its last state. Do I have to save the state of the previous activities separately to provide this behaviour? ``` ActivityA(FragmentA) -> ActivityA(FragmentB) -> ActivityB BACK ActivityA(FragmentB) ``` In the main activity I set the current fragment using: ``` FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.a_main_frame_content, new FragmentB()) .addToBackStack(null) .commit(); ``` From the fragment I start a new activity using: ``` Intent intent = new Intent(getActivity(), ActivityB.class); getActivity().startActivity(intent); ``` `ActivityA` is set as parent activity for `ActivityB` to provide proper navigation. [UPDTATE] It looks like the problem lies in the different behaviour of navigating back and navigating up. If I navigate back, the activity is displayed in its last state while navigating up forces the activity to recreate.

Original source