1

I implement the following code. It works, but I retrieve it more tha once, it makes many duplication in my data. How do I make it to run the retrieve more data just once?

final LinearLayoutManager layoutManager = (LinearLayoutManager) getLayoutManager();

recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
 boolean loading = true;

 @Override
 public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

     int pastVisibleItems, visibleItemCount, totalItemCount;
     visibleItemCount = layoutManager.getChildCount();
     totalItemCount = layoutManager.getItemCount();
     pastVisibleItems = layoutManager.findFirstVisibleItemPosition();

     if (loading) {
  if ((visibleItemCount + pastVisibleItems) >= totalItemCount) {
      loading = false;
      //retrieve more data from internet
      loading = true;
  }
     }
 }
});
Gustaf
  • 262
  • 1
  • 13

1 Answers1

1

It turns out below algorithm is better

private int previousTotal = 0;
private boolean loading = true;
private int visibleThreshold = 5;
int firstVisibleItem, visibleItemCount, totalItemCount;

mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {

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

        visibleItemCount = mRecyclerView.getChildCount();
        totalItemCount = mLayoutManager.getItemCount();
        firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();

        if (loading) {
            if (totalItemCount > previousTotal) {
                loading = false;
                previousTotal = totalItemCount;
            }
        }
        if (!loading && (totalItemCount - visibleItemCount) 
            <= (firstVisibleItem + visibleThreshold)) {
            // End has been reached

            Log.i("...", "end called");

            // Do something

            loading = true;
        }
    }
});

source

Community
  • 1
  • 1
Gustaf
  • 262
  • 1
  • 13