Endless Scrolling in RecyclerView (with JSON)- Weekly Series (Day4)

Those who are working with JSON and RecyclerView need endless scrolling for their app. It’s better to load the data automatically then showing pagination to the user, UX you know.

Actually, this thing is very easy to implement. You just need to add a scroll listener to your RecyclerView so that we can know when do we reach the bottom of the list.

First off, change your recyclerView’s layout manager from RecyclerView.LayoutManager to LinearLayoutManager.


RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);

Now attach addOnScrollListener to the RecyclerView.

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            // number of items that are currently visible on screen
            int currentItems = layoutManager.getChildCount();
            // number of items that you have scrolled
            int scrolledItems = layoutManager.findFirstCompletelyVisibleItemPosition();
            // total number of items
            int totalItems = layoutManager.getItemCount();
            // if this condition meets, load more data
            if(currentItems + scrolledItems == totalItems)
                // Load more. Create a new URL.
                String newUrl = "http://";  // Url to load next items.

Here "FetchData(String url)" is a custom function which uses Volley to load JSON data. Explanation of code is shown in the above code in comments.

JSON and Volley tutorial coming soon.

Leave a Reply

Your email address will not be published. Required fields are marked *