Home > Android Working with Load More RecyclerView and Bottom ProgressBar

Android Working with Load More RecyclerView and Bottom ProgressBar

When scroll RecyclerView to the end to get more data and update RecyclerView. When connect to get more data load more data is in progress at bottom.

In this article I will show you how to implement Load More RecyclerView with progress bar showing at bottom of RecyclerView.

Step 1. Create a new project in Android Studio from File => New Project and fill the project details.


Step 2. Open build.gradle add "recyclerview" & "cardview" library after adding click on Sync Now.

									
apply plugin: 'com.android.application' android { compileSdkVersion 26 buildToolsVersion "26.0.2" defaultConfig { applicationId "com.amisun.loadmorerecyclerview" minSdkVersion 15 targetSdkVersion 26 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } }

Step 3. Now open main_activity.xml add the RecyclerView like as below.

									
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.amisun.loadmorerecyclerview.MainActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/mRecyclerview" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>

Step 4. Now create a new recycler_view_item_row.xml file under res -> layout and modified layout as below.

								
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" card_view:cardUseCompatPadding="true" android:layout_margin="4dip"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" android:orientation="vertical"> <TextView android:id="@+id/txtEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="@android:color/black" android:textSize="16sp" android:text="Email Address" android:textStyle="bold" /> <TextView android:id="@+id/txtPhone" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="@android:color/black" android:text="9891952466" android:textSize="12sp" /> </LinearLayout> </android.support.v7.widget.CardView>


Step 5. Now create another new item_progressbar.xml file under res => layout and modified layout as below.

								
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <ProgressBar android:id="@+id/itemProgressbar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" /> </LinearLayout>

Step 6. Now create a new RecyclerView adapter class. In my case named RecyclerViewAdapter.java and modified adapter class as below.

								
package com.amisun.loadmorerecyclerview; /** * Created by qr on 25-Oct-17. */ import android.app.Activity; import android.content.Context; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import java.util.ArrayList; import java.util.HashMap; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{ private ArrayList<HashMap<String,String>> mDataset; private Context mcontext; private Activity mactivity; private OnItemClickListener listener; // for load more private final int VIEW_TYPE_ITEM = 0; private final int VIEW_TYPE_LOADING = 1; private OnLoadMoreListener onLoadMoreListener; // The minimum amount of items to have below your current scroll position // before loading more. private boolean isLoading; private int visibleThreshold = 5; private int lastVisibleItem, totalItemCount; public interface OnItemClickListener { void onItemClick(HashMap<String, String> item); } public interface OnLoadMoreListener { void onLoadMore(); } public void add(int position, HashMap<String,String> item) { mDataset.add(position, item); notifyItemInserted(position); } public void remove( HashMap<String,String> item) { int position = mDataset.indexOf(item); mDataset.remove(position); notifyItemRemoved(position); } // Provide a suitable constructor (depends on the kind of dataset) public RecyclerViewAdapter(Context context, ArrayList<HashMap<String, String>> myDataset, RecyclerView recyclerView) { mcontext = context; mactivity = (Activity)context; mDataset = myDataset; // load more final LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager(); recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); totalItemCount = linearLayoutManager.getItemCount(); lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition(); if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) { if (onLoadMoreListener != null) { onLoadMoreListener.onLoadMore(); } isLoading = true; } } }); } // Create new views (invoked by the layout manager) @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == VIEW_TYPE_ITEM) { View view = LayoutInflater.from(mactivity).inflate(R.layout.recycler_view_item_row, parent, false); return new ViewHolderRow(view); } else if (viewType == VIEW_TYPE_LOADING) { View view = LayoutInflater.from(mactivity).inflate(R.layout.item_progressbar, parent, false); return new ViewHolderLoading(view); } return null; } // Replace the contents of a view (invoked by the layout manager) @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // - get element from your dataset at this position // - replace the contents of the view with that element if (holder instanceof ViewHolderRow) { HashMap<String,String> map = mDataset.get(position); ViewHolderRow userViewHolder = (ViewHolderRow) holder; userViewHolder.txtEmail.setText(map.get("KEY_EMAIL")); userViewHolder.txtPhone.setText(map.get("KEY_PHONE")); //userViewHolder.email.setText(contact.getPhone()); // binding item click listner userViewHolder.bind(mDataset.get(position), listener); } else if (holder instanceof ViewHolderLoading) { ViewHolderLoading loadingViewHolder = (ViewHolderLoading) holder; loadingViewHolder.progressBar.setIndeterminate(true); } } // Return the size of your dataset (invoked by the layout manager) @Override public int getItemCount() { return mDataset == null ? 0 : mDataset.size(); } public void setOnLoadMoreListener(OnLoadMoreListener mOnLoadMoreListener) { this.onLoadMoreListener = mOnLoadMoreListener; } public void setOnItemListener(OnItemClickListener listener) { this.listener = listener; } @Override public int getItemViewType(int position) { return mDataset.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM; } public void setLoaded() { isLoading = false; } private class ViewHolderLoading extends RecyclerView.ViewHolder { public ProgressBar progressBar; public ViewHolderLoading(View view) { super(view); progressBar = (ProgressBar) view.findViewById(R.id.itemProgressbar); } } // Provide a reference to the views for each data item // Complex data items may need more than one view per item, and // you provide access to all the views for a data item in a view holder public class ViewHolderRow extends RecyclerView.ViewHolder { public TextView txtEmail, txtPhone; public ViewHolderRow(View v) { super(v); txtEmail = (TextView)v.findViewById(R.id.txtEmail); txtPhone = (TextView)v.findViewById(R.id.txtPhone); } public void bind(final HashMap<String,String> item, final OnItemClickListener listener) { itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.onItemClick(item); } }); } } }

Step 7. Now open MainActivity.java class file and modified as below.

								
package com.amisun.loadmorerecyclerview; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; public class MainActivity extends AppCompatActivity { ArrayList<HashMap<String,String>> getDatalist; private RecyclerView mrecyclerView; RecyclerViewAdapter mAdapter; private Random random; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); random = new Random(); getDatalist = new ArrayList<>(); for(int aind = 0 ; aind < 20; aind++){ HashMap<String,String> map = new HashMap<>(); map.put("KEY_EMAIL","android" + aind + "@gmail.com"); map.put("KEY_PHONE",phoneNumberGenerating()); getDatalist.add(map); } mrecyclerView = (RecyclerView) findViewById(R.id.mRecyclerview); mrecyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false)); mAdapter = new RecyclerViewAdapter(MainActivity.this, getDatalist, mrecyclerView); mrecyclerView.setAdapter(mAdapter); // set RecyclerView on item click listner mAdapter.setOnItemListener(new RecyclerViewAdapter.OnItemClickListener() { @Override public void onItemClick(HashMap<String, String> item) { String mEmail = ""; String mPhone = ""; try{ mEmail = item.get("KEY_EMAIL"); mPhone = item.get("KEY_PHONE"); }catch (Exception ev){ System.out.print(ev.getMessage()); } Toast.makeText(MainActivity.this,"Clicked row: \nEmail: "+mEmail+", Phone: "+mPhone,Toast.LENGTH_LONG).show(); } }); //set load more listener for the RecyclerView adapter mAdapter.setOnLoadMoreListener(new RecyclerViewAdapter.OnLoadMoreListener() { @Override public void onLoadMore() { if (getDatalist.size() <= 40) { getDatalist.add(null); mAdapter.notifyItemInserted(getDatalist.size() - 1); new Handler().postDelayed(new Runnable() { @Override public void run() { getDatalist.remove(getDatalist.size() - 1); mAdapter.notifyItemRemoved(getDatalist.size()); //Generating more data int index = getDatalist.size(); int end = index + 20; for (int i = index; i < end; i++) { HashMap<String,String> map = new HashMap<>(); map.put("KEY_EMAIL","android" + i + "@gmail.com"); map.put("KEY_PHONE",phoneNumberGenerating()); getDatalist.add(map); } mAdapter.notifyDataSetChanged(); mAdapter.setLoaded(); } }, 5000); } else { Toast.makeText(MainActivity.this, "Loading data completed", Toast.LENGTH_SHORT).show(); } } }); } private String phoneNumberGenerating() { int low = 100000000; int high = 999999999; int randomNumber = random.nextInt(high - low) + low; return "0" + randomNumber; } }

8. Output as below.

  • Camera Permission
  • External Storage Premission
  • Location Permission

Dheerendra Singh

Dheerendra Singh is a Mobile Developer(Android) & Web Developer(PHP) of Amisun IT Solutions, Master degree in Computer Science.


About Us

Amisun IT Solutions is an expert Software Development Company giving complete IT arrangements and going about as a seaward improvement community for abroad advancement firms.

We are an imaginative organization, situated in India that gives a progression of Web-based programming applications that have helped clients make fruitful online activities.

Our group of forward masterminds and reforming individuals tries to furnish you with the best of arrangements with flawlessness second to none. Our key concentration is dependably to furnish you with solid arrangements which are precisely planned and planned with stringent quality principles. ...   

Read more

Address

Shoppers Square Mall Shop No. 17 & 18, First Floor,
Shoppers Square Mall, Budhh Prakash Garg Marg, Block 14, Sector 10,
Raj Nagar, Ghaziabad, Uttar Pradesh 201002
P: (+91) 9899776200, (+91) 9899773200