title: How to get fragment references for Android FragmentPagerAdapter
body: <p>I'm using a ViewPager with a FragmentPagerAdapter to allow swiping between 2 fragments. I'm not using FragmentStatePagerAdapter because it destroys and recreates new fragment instances when swiping between them, and I don't want operations in one of the Fragments executing more than once). I need a way to get references to the 2 created fragments to pass to the FragmentPagerAdapter, but the following code is producing an error (see below):</p>
  
  <pre><code>public class MyActivity extends FragmentActivity {
  
      private ViewPager viewPager;
      private MyPagerAdapter pagerAdapter;
  
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_layout);
          initViewPager();
      }
  
      private void initViewPager() {
          List&lt;Fragment&gt; fragments = new ArrayList&lt;Fragment&gt;();
          FragmentManager fragManager = getSupportFragmentManager();
          fragments.add(fragManager.findFragmentById(R.id.fragment_1));
          fragments.add(fragManager.findFragmentById(R.id.fragment_2));
          pagerAdapter = new MyPagerAdapter(fragManager, fragments);
          viewPager = (ViewPager) findViewById(R.id.fragment_pager);
          viewPager.setAdapter(pagerAdapter);
      }
      ...
      ...
      private class MyPagerAdapter extends FragmentPagerAdapter {
  
          private List&lt;Fragment&gt; fragments;
  
          public MyPagerAdapter(FragmentManager fragmentManager, List&lt;Fragment&gt; fragments) {
                  super(fragmentManager);
                  this.fragments = fragments;
          }
  
          @Override
          public Fragment getItem(int position) {
              return fragments.get(position);
          }
          ...
          ...
  </code></pre>
  
  <p>This produces the following error (or similar):</p>
  
  <pre><code>java.lang.IllegalStateException: Can't change container ID of fragment Fragment1{4169f780 #1 id=0x7f0b0005 android:switcher:2131427331:0}: was 2131427333 now 2131427331
  </code></pre>
  
  <p>Can anybody help me with this?</p>
  
  <p><em><strong>Edit</em></strong><br>
  I've also tried the following, but it instantiates each fragment exactly twice (understandably), which I don't want. Other than that though, it works with this code:  </p>
  
  <pre><code>private void initViewPager() {
  
      List&lt;Fragment&gt; fragments = new Vector&lt;Fragment&gt;();
      fragments.add(Fragment.instantiate(this, Fragment1.class.getName()));
      fragments.add(Fragment.instantiate(this, Fragment2.class.getName()));
      pagerAdapter = new MyPagerAdapter(getSupportFragmentManager(), fragments);
      viewPager = (ViewPager) findViewById(R.id.fragment_pager);
      viewPager.setAdapter(pagerAdapter);
  }
  </code></pre>