I'm displaying a set of items in a RecyclerView
. The data are downloaded from the server, and one group of items are downloaded for each time. However, sometimes only one group of data cannot fill the screen, so I want to make the RecyclerView
capable of detecting this problem, and start loading next group of data until the screen is filled.
For example, if data of page 1 is not enough, load data of page 2. If still not, load data of page 3, and so on.
The detection part is not difficult since I can get the parameters below:
int visibleItemCount = mLayoutManager.getChildCount();
int totalItemCount = mLayoutManager.getItemCount();
int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();
But the problem comes with notifyDataSetChanged()
. For example, below is my code of setting data:
public void setData(List data){
updataData(data);
mAdapter.notifyDataSetChanged();
if(ifScreenNotFilled()){
loadNextGroupData(); // it calls 'setData()' recursively
}
}
When the loadNextGroupData()
is called, the setData
is called recursively. And it turns out that the size of data list keeps on expanding while the visibleItemCount
is always zero, and nothing appears on the screen.
If I delete the recursion part of code, the 1st group of data is loaded in to screen. I become very curious of the mechanism of notifyDataSetChanged()
.
So is there a solution to get the RecyclerView
updated automatically when it does not fill the screen?
I have found the reason why notifyDataSetChanged()
does not work. It's because the recursive invoking of the setData()
method making it never returns. Thus the notifyDataSetChanged()
could not be executed by the UI thread.
The solution is use a Handler
to post the recursive part into the message queue of UI thread.
mHandler = new Handler(Looper.getMainLooper());
public void setData(List data){
updataData(data);
mAdapter.notifyDataSetChanged();
if(ifScreenNotFilled()){
mHandler.post(new Runnable(){
@override
public void run(){
loadNextGroupData();
}
}
}
}
For those who may see this question later, the concrete implementaion of code above could be found in my repo: https://github.com/SphiaTower/AutoPagerRecyclerManager .
Please check the setData()
method in https://github.com/SphiaTower/AutoPagerRecyclerManager/blob/master/lib/src/main/java/tower/sphia/auto_pager_recycler/lib/AutoPagerRecyclerViewManager.java