NPE in Fragment.setUserVisibleHint() when using ViewPager

后端 未结 3 598
失恋的感觉
失恋的感觉 2021-01-11 17:32

I am at a loss for this. I am switching tabs manually in my ViewPager. I have this code inside my Activity:

@Override
public void onBackPressed()
{
    if (c         


        
3条回答
  •  一生所求
    2021-01-11 17:45

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

    Another way that I found to recreate error is to close activity/app, and quickly reopen page with the ViewPager 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();
            }
        }
    }
    

    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 - This solution fixes the NullPointerException for android.app.Fragment.setUserVisibleHint(Fragment.java:997) and should also work for android.support.v4.app.Fragment.setUserVisibleHint.

提交回复
热议问题