Search code examples
androidandroid-fragmentsfragment-lifecycle

Fragment lifecycle error in 4.4, onCreateView() is called on multiple fragments same time


I am getting error :

In error, Android framework is calling onCreateView() of multiple fragment at the same time

enter image description here

I have Navigation Drawer with 3 FrameLayout : A, B , C

1.) Through B Option of drawer, User reached to B2 Fragment.

2.)User presses Home Key on B2 fragment and goes to Home screen.

3.) User Long Press Home Key, opens this application from Recents Activity of Android

Here I am getting error which is shown in picture with 1 in Blue color

My multiple fragments are getting onCreate() , onCreateView() and onActivityCreated() events and so i am losing fragment state of B2 and my application goes to default fragment which is A1 (opening from drawer option A)

I have also saved my state of B2 with onSaveInstanceState() and restored with onActivityCreated() but this approach is not working because onActivityCreated() is called of B2 first and then A1 second. So, my B2 fragment is not visible on screen in foreground. Instead of this, A1 becomes visible on screen

Note :

I have used .replace() in switching fragments in all cases

This same code is running correct in Android 5.0+ (Lollipop) and gives error in 4.4 (and older version)

Can anybody suggest any workaround?


Solution

  • The problem was coming due to Developer Settings -> Do Not Keep Activities (Destroy every activity as soon as the user leaves it)

    enter image description here

    The abnormal behaviour was coming because I had turned this option ON

    This option will cause callback to onDestroy() method of every activity when user leaves it. In my case, i was using fragment so the events took place :

    Fragment.onSaveInstanceState()
    Activity.onStop()
    Fragment.onDestroyView()
    Activity.onDestroy()
    

    This option is OFF for users by default by manufecturers.

    This options has pros and cons described : Here