Search code examples
androidandroid-layoutandroid-recyclerviewbundle

How to restore to the previous state in RecyclerView after loading more data


I have been working with RecyclerView for a while. I am following lazy loading, so I am showing 10 data on the view each time. If user scroll to the bottom, the page re-load from the TOP! however, I want to stay where it was previously! So, I have tried to use

recyclerView.scrollToPosition(position);

However, this breaks the UI flow! My second try is using onSaveInstanceState() and onRestoreInstanceState(Bundle state); However, that does not work! My page is re-loads to the top!

Parcelable state = layoutManager.onSaveInstanceState();
layoutManager.onRestoreInstanceState(state);

I have tried every other methods, apparently none is working for me! Any help would be highly appreciated! Thanks in advance!


Solution

  • Note : Make sure that you are not initialising or calling setAdapter() method each time after updating your dataset. If not, then

    You have to update your data list and call notifyDataSetChanged() which will update your adapter from existing position.

    Let's say you have stored your data into ArrayList mData;

    Your getItemCount() would be

    @Override
    public int getItemCount() {
    
    if (mData != null && mData.length() > 0)
        return mData.size();
    
        return 0;
    }
    

    Now create one more method in your adapter which you will called each time whenever you will get new data from server. This method will simply override your dataset and will update your adapter

    private void updateDataSet(ArrayList<String> mData){
    
      this.mData = mData;
      notifyDataSetChanged();
    
    }