title: ViewPager retaing old Fragments on screen rotation
body: <p>I am using <code>ViewPager</code> and <code>FragmentStatePagerAdapter</code> to show fragment. Initially there are 2 fragments added Fragment1 and Fragment2 and 3rd fragment Fragment3 is added at 2nd position after recieiving response from server. So after all pages are added this should be sequence of Fragments in ViewPager --> Fragment1, Fragment3, Fragment2.</p>
  
  <p>The Problem is after Fragment1 and Fragment3 are added and app is making server call before adding 3rd Fragment at 2nd position if I do screen rotation multiple time then after 3rd fragment is added it still shows old copy of Fragment2 which was at 2nd position initially at 2nd position and 3rd position have new copy of Fragment2. So Fragment3 doest shows up in ViewPager. Sequence after adding 3rd Fragment -- > Fragment1, old copy of Fragment2, New Fragment2.</p>
  
  <p>I am overriding <code>onSaveInstanceState</code> and calling <code>super.onSaveInstanceState</code> in my Activity.</p>
  
  <p>Also I have tried returning <code>POSITION_NONE</code> from <code>getItemPosition</code>. I read somewhere that ViewPager save copies of fragment. Also through debugging I checked that ViewPager contained 2 copies of Fragment2 when issue was reproduced even though <code>getItem</code> of <code>FragmentStatePagerAdapter</code> returned different Fragments for each position but still at 2nd position it was showing old fragment. For testing purpose in <code>getItem</code> I returned Fragment1 for all positions so that all 3 pages should be same but even after that in 2nd position it was showing old copy of Fragment2 when I reproduced issue with steps mentioned above.</p>
  
  <p>So how to clear <code>ViewPager</code> so that it does not save old fragments. How to refresh ViewPager so that it does not retain old copy with fragments. I think problem is with onSaveInstanceState but I need it. How can I exclude <code>ViewPager</code> when views are saved in <code>onSaveInstanceState</code>. I have tried <code>mViewPager.setSaveEnabled(false)</code> but it takes too much memory.</p>
  
  <p>I found that the problem is <code>instantiateItem</code> method of adapter does not call getItem due to which old fragment is returned.</p>
  
  <p><strong>Below is solution code</strong></p>
  
  <p><strong>Code:</strong></p>
  
  <pre><code> @Override
          public Object instantiateItem(ViewGroup container, int position) {
              Object obj = super.instantiateItem(container, position);
              Fragment fragment = mFragments.get(position);
  
              if((obj!=null &amp;&amp; fragment!=null) &amp;&amp; !(obj.getClass().getSimpleName().equals(fragment.clss.getSimpleName()))){
                  destroyItem(container, position, obj);
                  return super.instantiateItem(container, position);
              }else{
                  return obj;
              }
          }
  </code></pre>