Search code examples
androidandroid-fragmentsandroid-viewpageractivity-lifecycle

Viewpager fragment reference to new copy after activity restore


When my activity containing viewpager is killed by system in background and then restores its state, fragments are correctly created and viewpager adapter can also point to them correctly. But when I get a fragment reference and try to access its fields, they are all null (checked by using breakpoint). I checked this by placing breakpoints in fragment onCreateView() and in my activity button's clickListener.

((WelcomeFragment)homeActivityFragmentPageAdapter.getItem(POSITION_HOME)).setdata(myData);

Now this method will through null pointer exception since setdata(data) is internally accessing arraylist field of fragment.

This creates a problem for me since, my activity has to continuously feed network data to the fragment by calling its public method (as suggested by documentation).

How to insure that after state restored; correct instance is pointed in my activity.


Solution

  • Try to use instantiateItem adapter method instead getItem.

    ((WelcomeFragment)homeActivityFragmentPageAdapter.instantiateItem(mViewPager, POSITION_HOME)).setdata(myData);
    

    Method getItem is overrided method, and common use is creation of child fragments.

    EDIT:

    In case of the question's scenario, you also need to store the state of FragmentStatePagerAdapter manually:

    @Override
        public void onSaveInstanceState(Bundle savedInstanceState) {
          savedInstanceState
            .putParcelable("pages",homeActivityFragmentPageAdapter.saveState());
          super.onSaveInstanceState(savedInstanceState);
        }
    

    Then you can retrieve the state in oncreate:

    @Override
        protected void onCreate(final Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
             if (savedInstanceState != null) {
                homeActivityFragmentPageAdapter.restoreState(savedInstanceState.getParcelable("pages"),this.getClassLoader());
                welcomeFragment = (WelcomeFragment) homeActivityFragmentPageAdapter.instantiateItem(mViewPager, POSITION_HOME);
    
            }
            else { //simply create a new instance here}
    
            homeActivityFragmentPageAdapter.addFragmentToAdapter(welcomeFragment);
            homeActivityFragmentPageAdapter.notifyDataSetChanged();
        }