Lazy Download recyclerView on Android

Does anyone know how to implement Lazy Loading recyclerView in android? I am new to android and I do not know how to understand this. I will be grateful if anyone helps.

+5
source share
1 answer

You can use EndlessRecyclerView

Overview A common feature of the application is to automatically load more elements when the user scrolls through the elements (or endless scrolling). This is done by running a request for more data as soon as the user crosses the threshold of the remaining elements before they reach the end.

The approaches to ListView, GridView, and RecyclerView (the successor to ListView) are described here. Both of them are similar in code, except that the LayoutManager in the RecyclerView must be passed in to provide the necessary information for implementing endless scrolling.

In both cases, the information needed to implement scrolling involves determining the last visible item in the list and some type of threshold value to start receiving more data before reaching the last item. This data can be used to determine when to load more data from an external source: To ensure that endless scrolling appears, it is important to get the data before the user reaches the end of the list. Therefore, adding a threshold value allows you to expect the addition of additional data.

Implementation with ListView or GridView
Each AdapterView (such as ListView and GridView) supports binding to OnScrollListener events, which are fired whenever a user scrolls a collection. Using this system, we can define a base EndlessScrollListener that supports most use cases by creating our own class that extends OnScrollListener:

import android.widget.AbsListView; public abstract class EndlessScrollListener implements AbsListView.OnScrollListener { // The minimum number of items to have below your current scroll position // before loading more. private int visibleThreshold = 5; // The current offset index of data you have loaded private int currentPage = 0; // The total number of items in the dataset after the last load private int previousTotalItemCount = 0; // True if we are still waiting for the last set of data to load. private boolean loading = true; // Sets the starting page index private int startingPageIndex = 0; public EndlessScrollListener() { } public EndlessScrollListener(int visibleThreshold) { this.visibleThreshold = visibleThreshold; } public EndlessScrollListener(int visibleThreshold, int startPage) { this.visibleThreshold = visibleThreshold; this.startingPageIndex = startPage; this.currentPage = startPage; } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // If the total item count is zero and the previous isn't, assume the // list is invalidated and should be reset back to initial state if (totalItemCount < previousTotalItemCount) { this.currentPage = this.startingPageIndex; this.previousTotalItemCount = totalItemCount; if (totalItemCount == 0) { this.loading = true; } } // If it still loading, we check to see if the dataset count has // changed, if so we conclude it has finished loading and update the current page // number and total item count. if (loading && (totalItemCount > previousTotalItemCount)) { loading = false; previousTotalItemCount = totalItemCount; currentPage++; } // If it isn't currently loading, we check to see if we have breached // the visibleThreshold and need to reload more data. // If we do need to reload some more data, we execute onLoadMore to fetch the data. if (!loading && (firstVisibleItem + visibleItemCount + visibleThreshold) >= totalItemCount ) { loading = onLoadMore(currentPage + 1, totalItemCount); } } // Defines the process for actually loading more data based on page // Returns true if more data is being loaded; returns false if there is no more data to load. public abstract boolean onLoadMore(int page, int totalItemsCount); @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // Don't take any action on changed } } 

Note that this is an abstract class and that to use it you must extend this base class and define the onLoadMore method to actually receive the new data. Now we can define an anonymous class as part of any action that extends the EndlessScrollListener and associates it with the AdapterView. For instance:

 public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // ... the usual ListView lvItems = (ListView) findViewById(R.id.lvItems); // Attach the listener to the AdapterView onCreate lvItems.setOnScrollListener(new EndlessScrollListener() { @Override public boolean onLoadMore(int page, int totalItemsCount) { // Triggered only when new data needs to be appended to the list // Add whatever code is needed to append new items to your AdapterView loadNextDataFromApi(page); // or loadNextDataFromApi(totalItemsCount); return true; // ONLY if more data is actually being loaded; false otherwise. } }); } // Append the next page of data into the adapter // This method probably sends out a network request and appends new data items to your adapter. public void loadNextDataFromApi(int offset) { // Send an API request to retrieve appropriate paginated data // --> Send the request including an offset value (ie `page`) as a query parameter. // --> Deserialize and construct new model objects from the API response // --> Append the new data objects to the existing set of items inside the array of items // --> Notify the adapter of the new items made with `notifyDataSetChanged()` } } 

Now, when scrolling, the elements will be automatically filled, because the onLoadMore method will be launched after the user crosses the visible Threshold. This approach works equally well for a GridView, and the listener provides access to both the page and the totalItemsCount to support paginated and offset based selection.

Implementation with RecyclerView We can use a similar approach with RecyclerView by defining the EndlessRecyclerViewScrollListener interface for which the onLoadMore () method should be implemented. The LayoutManager, which responds to the RecyclerView for rendering where the elements should be located and controls the scrolling, provides information about the current scroll position relative to the adapter. For this reason, we need to pass an instance that the LayoutManager is used to collect the necessary information to determine when to load more data. Implementing infinite pagination for RecyclerView requires the following steps:
Implementing infinite pagination for RecyclerView requires the following steps:
1. Copy the EndlessRecyclerViewScrollListener.java file to your application. 2. Call addOnScrollListener (...) in the RecyclerView to enable infinite pagination. Pass an instance of EndlessRecyclerViewScrollListener and implement onLoadMore, which runs whenever you need to load a new page to populate the list.
3. Inside the above onLoadMore method, load additional elements into the adapter either by sending a network request or by downloading from another source.

To start processing the scroll events for steps 2 and 3, we need to use the addOnScrollListener () method in our Activity or Fragment and pass the layout manager in the EndlessRecyclerViewScrollListener instance, as shown below:

 public class MainActivity extends Activity { // Store a member variable for the listener private EndlessRecyclerViewScrollListener scrollListener; @Override protected void onCreate(Bundle savedInstanceState) { // Configure the RecyclerView RecyclerView rvItems = (RecyclerView) findViewById(R.id.rvContacts); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); rvItems.setLayoutManager(linearLayoutManager); // Retain an instance so that you can call `resetState()` for fresh searches scrollListener = new EndlessRecyclerViewScrollListener(linearLayoutManager) { @Override public void onLoadMore(int page, int totalItemsCount, RecyclerView view) { // Triggered only when new data needs to be appended to the list // Add whatever code is needed to append new items to the bottom of the list loadNextDataFromApi(page); } }; // Adds the scroll listener to RecyclerView rvItems.addOnScrollListener(scrollListener); } // Append the next page of data into the adapter // This method probably sends out a network request and appends new data items to your adapter. public void loadNextDataFromApi(int offset) { // Send an API request to retrieve appropriate paginated data // --> Send the request including an offset value (ie `page`) as a query parameter. // --> Deserialize and construct new model objects from the API response // --> Append the new data objects to the existing set of items inside the array of items // --> Notify the adapter of the new items made with `notifyItemRangeInserted()` } } 

https://github.com/codepath/android_guides/wiki/Endless-Scrolling-with-AdapterViews-and-RecyclerView

+3
source

Source: https://habr.com/ru/post/1244765/


All Articles