Skip to content Skip to sidebar Skip to footer

Limited Access In 2nd Fragment Of Fragmentpageradapter

I have two similar by onViewCreated structure fragments //1st @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated

Solution 1:

If you look at the Fragment lifecycle, you'll see that there's an onAttach() and an onDetach() methods. They refer to the Fragment's state. Since you're using a ViewPager, your fragments might be detached and the getActivity() might return null.

As stated on this article, this is what happens with a Fragment inside a ViewPager:

When the page is no longer visible or adjacent to the visible page the ViewPager asks the adapter to destroy it. However the FragmentPagerAdapter doesn't destroy the fragment entirely. It calls FragmentTransaction.detach(fragment), which destroys the fragment's entire view hierarchy, but not the object. Next time the ViewPager wants that page the same fragment object can be retrieved and the view is rebuilt. In the process the onCreateView() is called again, this is where your logic to initialise the view belongs.

And as stated on the docs:

Caution: If you need a Context object within your Fragment, you can call getContext(). However, be careful to call getContext() only when the fragment is attached to an activity. When the fragment isn't attached yet, or was detached during the end of its lifecycle, getContext() returns null.

One thing you can try is to retain the fragment instance. Inside your Fragment's onCreate(), try to call the method setRetainInstance(true);

Also, check this answer and this other one here on SO, it might be useful for your use case.

Solution 2:

Another solution as @Mauker suggested via onAttach()

getActivity() returns null on fragment?

but instead of adding mcontext=getContext(); to each Fragment start added this to own class extention of FragmentPagerAdapter

publicclassTabAdapterextendsFragmentPagerAdapter {

finalintPAGE_COUNT=2;
private Context mContext;

publicTabAdapter(Context context, FragmentManager fm) {
    super(fm);
    mContext = context;
}

Post a Comment for "Limited Access In 2nd Fragment Of Fragmentpageradapter"