I am using a tabbed Activity
provided by Android with android.support.v7.app.ActionBar.TabListener
,ViewPager
and FragmentPagerAdapter
. The parent Activty
cointains and manages three Fragment
. In addition, the parent Activity has a method to save the data provided by the fragments. In order to get the data defined in them (and not sended by the parent Activity) I am wrote the following code:
MyFragment frag = (MyFragment) mSectionsPagerAdapter.getActiveFragment(mViewPager,1,getSupportFragmentManager());
Where getActiveFragment()
is
public Fragment getActiveFragment(ViewPager container, int position, FragmentManager mFragmentManager) {
String name = makeFragmentName(container.getId(), position);
return mFragmentManager.findFragmentByTag(name);
}
private String makeFragmentName(int viewId, int index) {
return "android:switcher:" + viewId + ":" + index;
}
Actually, I have the following problem: when I try to save data provided by the three fragment, I have a java.lang.NullPointerException
caused by the third fragment which is null. This happens only if I do not display on my device the second or third fragment.
I do not understand how to avoid and fix this behaviour.
Any suggestion?
This is due to the third fragment not being created if only the first tab/fragment is shown. The ViewPager per default internally prepares the visible fragment, the one left to it and the one right to it. Try