androidandroid-fragmentstransactionmanager

Resuming a dead app from background is making it behave weirdly


I am building an application which has the following structure.

MainActivity -> Fragment1
             -> Fragment2 -> Fragment3

Here Fragment1 is hosted on MainActivity in FrameLayout. when user click any option on Fragment1, I am switching to Fragment2 which hosts Fragment3 on ViewPager.

Problem is, if user moves to android home without closing the app, and in a duration of time the app is killed by Android, and user tries to resume the app from recent app list, Fragment3 is displaying the blank screen.

here is the method which I am using for Fragment transaction

public void requestChangeFragment(Fragment newFragment,String tag,Fragment oldFragment, int anim_in, int anim_out){
        if(isStopped()){
            return;
        }
        mFragmentManager = getSupportFragmentManager();
        android.support.v4.app.FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        fragmentTransaction.setCustomAnimations(anim_in,anim_out,anim_in,anim_out);
        fragmentTransaction.add(R.id.main_frame_layout, newFragment, tag);
        Log.i("FragMngr","Animations set in "+anim_in+" out "+anim_out);
        fragmentTransaction.addToBackStack(tag);
        int count = mFragmentManager.getBackStackEntryCount();
        String log="";
        fragmentTransaction.commit();
        for(int i=0;i<count;i++){
            android.support.v4.app.FragmentManager.BackStackEntry backStackEntry = mFragmentManager.getBackStackEntryAt(i);
            log += "count "+i+" name "+backStackEntry.getName()+"\n";
        }
        Log.d("FragMngr","BackStack trace after adding is\n "+log);
        if(oldFragment!=null) {
            if(oldFragment.isResumed()) {
                oldFragment.onPause();
            }
        }
        topFragment = newFragment;
    }

requestChangeFragment() is called from running fragments with the help of interface implemented in MainActivity.


Solution

  • After doing some research I identified the problem to be the saved instances which stores the current state of the fragment whenever android garbage collector kills the app when app is not in use. So when I tried to resume the dead app, it moves the fragment that was selected before pausing the app. But the fragment do not have any data which it must have received from the it Main class.

    Solution : Clear the saved instances in your MainActivity in onCreate method. Or if you are storing any values in your saved instance state, then perform the operation related to the saved Instance State, clear the value and then call super.onCreate(savedInstanceState)