Skip to content Skip to sidebar Skip to footer

Android.support.v4.app.Fragment.setUserVisibleHint Null Pointer On App Resuming

I am getting a crash on the resume of the app in the fragments code. I have never seen this crash myself but I have received crash reports back from users via TestFlight. I guess t

Solution 1:

Finally! I'm now able to reliably recreate this error!

To recreate error, close activity/app, and quickly reopen page with fragment. You may have to try a few times because in my tests I had to reopen the app within about 30ms. This time may be slower or faster for different speed devices.

The problem was that I only explicitly created the Fragment (using new) once, and kept a reference to that instance so that I could reuse it. One simple fix to this problem is to always return a new instance of the Fragment the FragmentPagerAdapter.getItem(...), as shown below.

public class ViewPagerAdapter extends FragmentPagerAdapter {
    ...

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0: return mMyFragment; // Error. Has the edge-case crash.
            case 1: return new MyFragment(); // Works.
            default: return new MyDefaultFragment();
        }
    }
}

For the OP's specific case, using the List<Fragment> to hold references is likely the same problem case as above.

ps - The root problem likely has something to do with the Fragment lifecycle and trying to use it again while it's being destroyed.

pps - Another way to recreate error is to quickly switch between enough tabs so that the Fragment wants to be destroyed to free some memory from cache, then quickly go back to it. By default, the FragmentPagerAdapter only caches one Fragment to the "left" and "right". So, depending on your cache limit, you will have to have at least three tabs to recreate the error this way.

ppps - This solution fixes the NullPointerException for android.app.Fragment.setUserVisibleHint(Fragment.java:997) and should also work for android.support.v4.app.Fragment.setUserVisibleHint.


Solution 2:

I don't think there is enough information provided to answer your question. I would like to see the exact line on your code that is causing a null pointer.

Anyway, looking through your code, the only culprit I can guess can cause you problems is the getItem() where you are passing null:

    @Override
public Fragment getItem(int aPosition)
{
    if (mFragments.size() > aPosition)
        return mFragments.get(aPosition);

    return null;
}

You should be able to just return mFragments.get(aPosition) since you already have overriden getCount().


Post a Comment for "Android.support.v4.app.Fragment.setUserVisibleHint Null Pointer On App Resuming"