0

I have an app which has a dashboard containing a Google map (SupportMapFragment) and a few counters being automatically updated by attached sensors. They record a bike ride. Let's call this fragment A.

I have a couple other fragments with for example settings, a list with previous rides. Let's call them to fragment B, C, D.

The fragments are being placed inside a FrameLayout inside a DrawerLayout (with a NavigationView) when pressing an item in the navigation view the fragment changes. This works fine, only that when returning to fragment A a new view is created with a clean map (aka not containing a trace line of the currently recorded ride), and empty sensors.

Fragment A always gets created on the creation of the drawer layout activity. Fragments B/C/D get created over this, when onBackPressed or the dashboard item is pressed in the menu those fragments get popped from the back stack and only A remains.

My question is the following: How can I keep the views inside Fragment A active/in memory so the line on the map continues to be drawn while visiting another fragment? And they are still there when I come back to fragment A?

I achieved the same thing when I had a separate activity for the dashboard and using the android:launchMode="singleInstance" modifier in the manifest. One of the things I also tried is placing setRetainInstance(true) inside fragment A.

Thanks in advance.

Puja
  • 192
  • 9
genie137
  • 23
  • 1
  • 8

2 Answers2

1

This a typical Android lifecycle issue. You don't have control over the fragment once you have replaced it with another and Android will quietly destroy it in the background.

You need to save the fragment state by implementing Fragment#onSaveInstanceState(Bundle) and one of the methods to restore the state when the Fragment is recreated, e.g. onCreate(Bundle), onCreateView(LayoutInflater, ViewGroup, Bundle), onActivityCreated(Bundle), or onRestoreInstanceState(Bundle). This seems like hard work, but it's standard practice for Android and something you'd need to implement for, say, configuration changes where the entire activity is torn down and restarted from scratch.

There's an outline on how to save/restore the fragment state here: Once for all, how to correctly save instance state of Fragments in back stack?

AGDownie
  • 528
  • 4
  • 9
0

Your fragment on back stack is still alive, just its view has been destroyed. So I solve this issue by saving view as an private variable and reuse after restoring from backstack:

public class MyFragment extends Fragment {
    private View view;

    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
        if(view != null) {
            return view;
        }
        view = inflater.inflate(R.layout.fragment_layout, container, false);

        // do your view initialization here ...

        return view;
}

The lifecycle of a fragment whenever pushed and restored from backstack