Anser Abbas
Anser Abbas

Reputation: 59

How to implement pagination in recyclerview?

I am performing pagination in recyclerView. My data is loading successfully and problem is how can I request to server for the next page. How i can perform pagination and how i can find page number which is being scrolled.

My code is:

rvLatestProduct.addOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            //super.onScrolled(recyclerView, dx, dy);

            visibleItemCount = rvLatestProduct.getChildCount();
            totalItemCount = linearLayoutManager.getItemCount();
            firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition();
            Log.e("totalItemCount",String.valueOf(totalItemCount));
            if (loading) {
                if (totalItemCount > previousTotal) {
                    loading = false;
                   // currentPage += 1;
                    previousTotal = totalItemCount;
                    Log.e("previousTotal",String.valueOf(previousTotal));
                }
            }
            if (!loading && (totalItemCount - visibleItemCount)
                    <= (firstVisibleItem + visibleThreshold)) {
                //int initialSize = totalItemCount.size;
                getPagination();
                //val updatedSize = dataList.size
              //  recyclerView.post { adapter.notifyItemRangeInserted(initialSize, updatedSize) }
                loading = true;
            }
        }
    });

and getPagination(); code is given as

  private void getPagination(){
    final JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET,
            AllURLs.viewAllLatestProduct,null,
            new Response.Listener<JSONArray>() {
                JSONArray object;
                @Override
                public void onResponse(JSONArray response) {
                    try {
                        for (int i=0;i<response.length();i++) {
                          object = response.getJSONArray(i);
                        }
                        setLatestProductAdapter(object);
                        adapter.notifyDataSetChanged();
                       // Toast.makeText(context,"page no" + pageNo,Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    VolleySingleton.getInstance(context).addToRequestQueue(request);
}

Upvotes: 4

Views: 9364

Answers (3)

Rohit Singh
Rohit Singh

Reputation: 18222

Call the next page at the end of scroll.

You can determine when the recycler view is scrolled to the last element. And then you can send a request for the next page. When the next page returns new results add them in the previous result set and update the list.

enter image description here

More explanation with RecyclerView

How to implement pagination in RecyclerView on scroll

Demo Project

Github Link

enter image description here

Upvotes: 0

Sukhbir
Sukhbir

Reputation: 1608

In API url take a parameter count, whenever getPagination() method is called you can send increased value in count parameter. According to that count parameter on server side you can add logic to get next items.

See how to pass parameter in Api using volley

StringRequest strreq = new StringRequest(Request.Method.POST,
     "http://196.1.1.1/myurl",
      new Response.Listener<String>() {
         @Override
         public void onResponse(String Response) {
                  // get response
         }
      }, new Response.ErrorListener() {
         @Override
         public void onErrorResponse(VolleyError e) {
            e.printStackTrace();
         }
}){@Override
    public Map<String, String> getParams(){
      Map<String, String> params = new HashMap<>();
      params.put("Count", count);
      return mParams;
 }
  }; 
Volley.getInstance(this).addToRequestQueue(strreq);

Hope this will help.

Upvotes: 0

Jaymin
Jaymin

Reputation: 2912

Try below code

// Define variable in class 

private int page = 1, limit = 15;
private int firstVisibleItem, visibleItemCount, totalItemCount;
private int previousTotal = 0;
private int visibleThreshold = 10;

Code for recyclerView scroll listener:

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) {
                    super.onScrolled(recyclerView, dx, dy);
                    if (dy > 0) {
                        mLinearLayoutManager = (LinearLayoutManager) recyclerLikedItemsList
                                .getLayoutManager();

                        if (!CheckInternet
                                .checkInternetConnection(AllLikedItemList.this)) {
                            //show connection error


                        } else {

                            visibleItemCount = recyclerView.getChildCount();
                            totalItemCount = mLinearLayoutManager
                                    .getItemCount();
                            firstVisibleItem = mLinearLayoutManager
                                    .findFirstVisibleItemPosition();

                            if (loading) {
                                if (totalItemCount > previousTotal) {

                                    previousTotal = totalItemCount;
                                    page++;
                                }
                            }
                            if (!loading
                                    && (firstVisibleItem + visibleThreshold + visibleItemCount) >= totalItemCount) {
                                page++;
                                // call pagination and pass page limit
                                 getPagination();

                            }
                        }

                    }
                }
            });

Upvotes: 0

Related Questions