Search code examples
javaandroidandroid-fragmentsandroid-viewpager

Android app fragments in viewpager become detached for no apparent reason


I'm writing an android application that uses a ViewPager to contain 3 screens that can be accessed via swiping left and right. These tabs are defined as fragment subclasses with separate XML files. It works, but for some reason whenever I unplug my device or connect/disconnect a bluetooth input device (possibly other things but these are the main causes I've seen) the fragments become detached, and the screen goes white, then the app crashes with this error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{me.samboycoding.<snip>/me.samboycoding.<snip>.MainActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f08006d (me.samboycoding.<snip>:id/pager) for fragment TabDeviceOverview{d0b5892 #0 id=0x7f08006d android:switcher:2131230829:0}

I've got no idea why this happens. I've tried setting setRetainInstance to true, and I've also tried using the fragment manager to store my fragment, but to no avail. Firstly, is there no way to ensure a fragment is kept loaded - as I think that's what's happening here, and secondly if not, how do I go about detecting this state and recreating the view?

I can post code if desired, just tell me what to post.

Adapter class: https://hastebin.com/zayewipimo.java

Relevant part of my onCreate: https://hastebin.com/gubikixude.java


Solution

  • 1) remove this line:

    pager.setOffscreenPageLimit(2);
    

    it will cause fragments to retain it's view rather than recreating it's view.

    2) change in your adapter class:

    extends the FragmentStatePagerAdapter class

    PageAdapter extends FragmentStatePagerAdapter
    

    3) overide the getItemPosition() in your adapter class and make it return POSITION_NONE.

      @Override
        public int getItemPosition(Object object) {
    
            return POSITION_NONE;
        }