Background
I have the next scenario:
- There is a navigation drawer with items. each switches to a different fragment.
- One of the fragments holds a viewPager, which holds fragments.
- Each of the viewPager's fragments have a ListView in it.
- When the user switches between the pages of the viewPager, or goes to another navigation-drawer fragment, and then back to one of the viewPager's fragment, the ListView should be restored to its original state.
All that I've used is via the support library.
The problem
It seems that this situation doesn't work well with the support library, and I get various exceptions, for example :
NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference viewpager
What I've found
I've found out that this issue is known (link here) .
What I've done (and it works) is this:
- the fragment with the viewPager holds all of the fragments instances.
- each fragment in the viewpager holds its inflated view and returns it in case onCreateView is called.
- each fragment in the viewpager saves&restores its saved-state like on normal fragments.
- the adapter I use for the viewPager extends from "FragmentStatePagerAdapter" , and it has a function "restoreState" that it overrides which won't call "super.restoreState()" .
- the activity that switches between the fragments holds a reference to the fragment with the viewPager.
This is quite wasteful (storing the reference to fragments and views), but it works.
The question
Is there any better solution than that?