Search code examples
androidandroid-recyclerviewandroid-appcompatonscrolllistener

RecyclerView OnScrollListener() Issue


I have around 32 records in json, I am using RecyclerView to show them and I have implemented OnScrollListener(...)

Question

I started an Activity, I fetched all 32 records, now when I do scroll, why I am again getting same 32 records again and again, whenever I do scroll, here is my implementation of OnScrollListener()

public void initializeOnScrollForRecyclerView() {
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

                int visibleItemCount = recyclerView.getLayoutManager().getChildCount();
                int totalItemCount = recyclerView.getLayoutManager().getItemCount();
                int pastVisiblesItems = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();

                if (!isLoading) {
                    if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                        isLoading = true;
                        mPostPresenter.loadPosts(false);
                    }
                }
            }
        });
    }

Solution

  • The Implementation seems to be correct but for one condition it fails, try when dy > 0 like this (Also put this in the OnCreate of the Activity) :

        private boolean loading = true;
    
     recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
    
    
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy)
            {
    
                if (loading) {
                    if (dy > 0) //check for scroll down
                    {
                        visibleItemCount = layoutManager.getChildCount();
                        totalItemCount = layoutManager.getItemCount();
                        pastVisiblesItems = layoutManager.findFirstVisibleItemPosition();
    
                        if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                            loading = false;
    
                            Log.v("...", " Reached Last Item");
                            loadMoreVideos(searchVideos);
                        }
    
                    }
                }
            }
        });