Challenge 2 - Extra calls for more pages

I’m using the following OnScrollListener to pull more pages from Flickr, but I’m finding that sometimes it’s executing the FetchItemsTask several times on one scroll to bottom. I’m thinking this has to do with the delay in receiving the new page/updating UI, but not sure if anyone has any suggestions to prevent this?

mPhotoRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
GridLayoutManager manager = (GridLayoutManager)mPhotoRecyclerView
.getLayoutManager();

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            mLastPosition = manager.findLastVisibleItemPosition();
            if(mLastPosition == mItems.size() - 1){
                Toast.makeText(getActivity(), "Bottom", Toast.LENGTH_SHORT).show();
                new FetchItemsTask().execute();
            }
        }
    });

This seems to have been solved by using a member variable (mUserScrolled) to track if the user has scrolled. It’s declared as false, and the if within onScrolled will only run if it is false. onScrolled now updates mUserScrolled to true to prevent additional executions of FetchItemsTask. mUserScrolled is then set to false again in the onPostExecute.

@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
mLastPosition = manager.findLastVisibleItemPosition();
if(!mUserScrolled){
if(mLastPosition == mItems.size() - 1){
mUserScrolled = true;
Toast.makeText(getActivity(), “Bottom”, Toast.LENGTH_SHORT).show();
new FetchItemsTask().execute();
}
}
}

@Override
protected void onPostExecute(List items) {
for(GalleryItem item: items) {
mItems.add(item);
}
mUserScrolled = false;
setupAdapter();
}

2 Likes