2

In my application I have 3 fragments in a viewPager. For the first fragment I would like to reload the view after a button press (basically call again the onCreateView()).

To get this functionality I decided to use FragmentTransaction, detach(), attach() and commit() the fragment.

In fragment I have created SetData() method:

public void setData() {
    Fragment frg = null;
    frg = mainMenu.getFragmentByPosition();
    final android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.detach(frg);
    ft.attach(frg);
    ft.commit();
}

In the activity which holds the viewPager I have getFragmentByPosition() method:

public Fragment getFragmentByPosition() {
    String tag = "android:switcher:" + R.id.viewpager + ":" + viewPager.getCurrentItem();
    return getSupportFragmentManager().findFragmentByTag(tag);
}

The problem is that I get NullPointerException in getFragmentByPosition()

UPDATE

The problem is that I cannot get the reference to a currently shown fragment.

adapter.getItem(1) - returns null

getFragmentManager().getFragments().get(0) - returns null

1 Answers1

0

If you have 3 fragments, create 3 unique strings TAG1, TAG2, TAG3 and then add each fragment using his unique tag

getSupportFragmentManager().beginTransaction().add(R.id.mycontainer, new MyFragment1(), TAG1).commit();

Then find using the same tags

getSupportFragmentManager().findFragmentByTag(TAG1);
Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158
  • Does it also work this way if the fragments are in FragmentPagerAdapter? – user3844748 May 05 '16 at 20:36
  • FragmentPagerAdapter gives a fragment for a position given. getItem(1) shall always be returning your first fragment, getItem(2) the second etc. No tags at all. – Alexander Kulyakhtin May 05 '16 at 20:50
  • The problem is that the adapter.getItem(1) have also NullPointerException. – user3844748 May 05 '16 at 22:26
  • OK, currently the NullPointerException is in SetData() method (I have changed the previous code) - getFragmentManager().beginTransaction().detach(frag).attach(frag).commit(); frag is the fragment passed from adapter.getItem(1). – user3844748 May 05 '16 at 22:43