0

I am Using the MVVM pattern with Room Database. In one of the Screen there are 3 Tabs with FragmentPagerAdapter viewPager. Now I am able to save and Retrieve from Database in My Fragments. But I also Want to save the Scroll state of Recycler Views which are inside all the 3 tabs.

So, Each fragment is going to Use a different Method to get LiveData from Dao. So each query is being observed by 1 Fragment Only. Now ViewPager has default value of viewPager.setOffscreenPageLimit(); is 1 by default. Now I want to save the scroll state of each fragment even after paused and coming back.

Below is the code for fragments to observe the Livedata which is common in all tabs:

mViewModel.getLiveFlights().observe(getViewLifecycleOwner(), flightGroups -> adapter.submitList(flightGroups));

I have Tried Saving the LinearLayoutManager State and retrieving it later by following code:

@Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        Log.e(TAG,"onViewStateRestored");
        if(savedInstanceState != null)
        {
            Parcelable savedRecyclerLayoutState = savedInstanceState.getParcelable(BUNDLE_RECYCLER_LAYOUT);
            if(savedRecyclerLayoutState != null && recyclerView.getLayoutManager() != null)
                recyclerView.getLayoutManager().onRestoreInstanceState(savedRecyclerLayoutState);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.e(TAG,"onSaveInstanceState");
        if(recyclerView.getLayoutManager() != null)
            outState.putParcelable(BUNDLE_RECYCLER_LAYOUT, recyclerView.getLayoutManager().onSaveInstanceState());
    } 

EDIT: I got the above code using: https://stackoverflow.com/a/29166336

Nishant Garg
  • 135
  • 9
  • Are you calling `mViewModel.getLiveFlights().observe...` this line in `onCreateView()`? – Sanlok Lee May 25 '19 at 05:51
  • Nope. It is in `onActivityCreated()` – Nishant Garg May 25 '19 at 06:25
  • Have you checked whether the observer is notified (in other words, `adapter.submit()` is called) before or after `onViewStateRestored()`? – Sanlok Lee May 25 '19 at 06:34
  • Hmm. That is not something I checked. But I did check `onViewStateRestored()` is getting called and `onSaveInstanceState()` never gets called. – Nishant Garg May 25 '19 at 06:37
  • If `onSaveInstanceState` is the problem https://stackoverflow.com/a/21439590/6587143 this suggests switching to FragmentStatePagerAdapter. If `onSaveInstanceState` is still not called I guess you might have to manually get the position in `onPause` and put it back in `onResume` – Sanlok Lee May 25 '19 at 06:49
  • Also you probably want to make sure `adapter.submit` is called at least once before restoring the position otherwise it might try to restore on an empty `RecyclerView`. – Sanlok Lee May 25 '19 at 06:51

0 Answers0