title: Accessing Fragment from viewpager returns null everytime?
body: <p>My host activity has a viewpager with two fragments A and B.My activity code looks like this:</p>
  
  <pre><code>public class MainActivity extends AppCompatActivity implements
          OnDataLoadedListener {
  
      private ViewPager pager;
      private MyPagerAdapter adapter;
  
  @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          pager = (ViewPager) findViewById(R.id.pager);
          adapter = new MyPagerAdapter(getSupportFragmentManager());
          pager.setAdapter(adapter);
  
          final int pageMargin = (int) TypedValue.applyDimension(
                  TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
                          .getDisplayMetrics());
          pager.setPageMargin(pageMargin);
          tabLayout.setupWithViewPager(pager);
  }
  
  
  public class MyPagerAdapter extends FragmentPagerAdapter {
  
          private final String[] TITLES = { "A",
                  "B" };
  
          public MyPagerAdapter(FragmentManager fm) {
              super(fm);
          }
  
          @Override
          public CharSequence getPageTitle(int position) {
              return TITLES[position];
          }
  
          @Override
          public int getCount() {
              return TITLES.length;
          }
  
          @Override
          public Fragment getItem(int position) {
              switch (position) {
  
              case 0:
                  return A.getInstance();
              case 1:
                  return B.getInstance();
              }
              return null;
          }
  
      }
  
  public Fragment findFragmentByPosition(int position) {
          return getSupportFragmentManager().findFragmentByTag(
                  "android:switcher:" + pager.getId() + ":"
                          + adapter.getItemId(position));
      }
  </code></pre>
  
  <p>Now when activity start viewpager get populated with fragment properly and I try to access fragmentby using following code:</p>
  
  <pre><code>if (AFragment == null)
      AFragment = (A) findFragmentByPosition(0);
  if (BFragment == null)
      BFragment = (B) findFragmentByPosition(1);
  </code></pre>
  
  <p>But <strong>AFragment</strong> and <strong>BFragment</strong> always contains null.I have read other simmilar <a href="https://stackoverflow.com/questions/25116800/access-viewpager-fragment-from-host-activity-returns-fragment-as-null">question</a> but it didn't help either.I need access to fragments as I want to call some methods defined in fragment from host activity.</p>
  
  <p><strong>Code to get an instance of fragment:</strong></p>
  
  <pre><code>public static AFragment getInstance() {
          AFragment fragment = new AFragment();
          return fragment;
      }
  </code></pre>