Android MySQL Retrofit Full Course – INSERT SELECT UPDATE DELETE SEARCH PAGINATION → Listing Scientists in a RecyclerView with Loadmore Pagination – Camposha


Listing Scientists in a RecyclerView with Loadmore Pagination

Listing Scientists in a RecyclerView


We are creating a full android mysql crud app. Some of the functionalities of the app include listing scientists in a recyclerview. We will however be paging/paginating our data. This pagination will occur at the server side. We will also add a search functionality.

Concepts You will Learn

By the end of this lesson you will have learnt the following:

  1. How to render data on a recyclerview.
  2. How to perform a Load more pagination on a recyclerview.
  3. How to perform a search filter on mysql data.

NB/= Pagination and Search will occur at the server side. We’ll had looked at that in a PHP class earlier.

Step 1.

Create a file called and add the following code imports:

package info.camposha.retrofitmysqlcrud.Views;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AbsListView;
import android.widget.ProgressBar;

import java.util.ArrayList;
import java.util.List;

import info.camposha.retrofitmysqlcrud.Helpers.MyAdapter;
import info.camposha.retrofitmysqlcrud.Helpers.Utils;
import info.camposha.retrofitmysqlcrud.R;
import info.camposha.retrofitmysqlcrud.Retrofit.ResponseModel;
import info.camposha.retrofitmysqlcrud.Retrofit.RestApi;
import info.camposha.retrofitmysqlcrud.Retrofit.Scientist;
import io.github.inflationx.viewpump.ViewPumpContextWrapper;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

Then create class below those imports:

public class ScientistsActivity extends AppCompatActivity

Make it implement the following interfaces:

public class ScientistsActivity extends AppCompatActivity
        implements SearchView.OnQueryTextListener,MenuItem.OnActionExpandListener{

We’ve just created a class extending AppCompatActivity. We’ve then made it implement two interfaces:

  1. OnQueryTextListener – To listen to text change events of our serachview.
  2. OnActionExpandListener – Raised when a menu item is expanded.

Then define our instance fields:

     //We define our instance fields
    private RecyclerView rv;
    private MyAdapter mAdapter;
    private LinearLayoutManager layoutManager;
    public ArrayList<Scientist> allPagesScientists = new ArrayList();
    private List<Scientist> currentPageScientists;
    private Boolean isScrolling = false;
    private int currentScientists, totalScientists, scrolledOutScientists;
    private ProgressBar mProgressBar;

You can see we’ve declared Recyclerview which is our adapterview. The MyAdapter is our RecyclerView adapter. LinearLayoutManager will allow us position items in our recyclerview.
allPagesArrayList will hold all the scientists that have been downloaded so far.

currentPageScientists will hold the current scientists as we paginate our data. For example if we are in page 3, then this arraylist will hold data for page alone while allPagesScientsits will hold data for pages 1,2 and 3.

isScrolling will tell us when the user is scrolling the recyclerview. By default we set it to false.

currentScientists tell us the current page.It’s an intger as are totalScientists and scrolledOutScientists.

Our ProgressBar will be shown while we are downloading our data.

Add this method after the declarations above:

    private void initializeViews() {
        mProgressBar = findViewById(;
        rv = findViewById(;

The above method is just referencing our views like progress bar and recyclerview.

Then add the following code:

     * This method will setup oir RecyclerView
    private void setupRecyclerView() {
        layoutManager = new LinearLayoutManager(this);
        mAdapter = new MyAdapter(this, allPagesScientists);

The above method is setting up our recyclerview. First we instantiate our LinearLayoutManager,then our adapter and set them to our recyclerview.

Then create a method like below:

     * This method will download for us data from php mysql based on supplied query string
     * as well as pagination parameters. We are basiclally searching or selecting data
     * without seaching. However all the arriving data is paginated at the server level.
    private void retrieveAndFillRecyclerView(final String action, String queryString,
     final String start, String limit) {

That method, as the name suggests will fetch our data from mysql and populate our recyclerview. However alot of things will happen in this method. You can see we are passing 4 strings.

They include:

  1. action – The action we want to perform. Whether it’s downloading all data or downloading paged data. The above method is capable of both.
  2. queryString – We said we will be searching against MySQL. Well this is the query or search term that we pass over to be sent to the server.
  3. start – Where we are starting our pagination. it’s also called offset. For example, are we starting pagination at row number 5, row number 10 or what. That is the offset.
  4. limit – The number of rows we are fetching.

Then add the following code in the method:

        mAdapter.searchString = queryString;
        RestApi api = Utils.getClient().create(RestApi.class);
        Call<ResponseModel> retrievedData;

We have set our search string to a variable in our adapter. There it will be highlighted as we search. Then we have instantiated our RestApi using the create() method. Then we’ve defined a Retrofit2.Call object.

Then add the following code:

        if (action.equalsIgnoreCase("GET_PAGINATED")) {
            retrievedData ="GET_PAGINATED", queryString, start, limit);
        } else if (action.equalsIgnoreCase("GET_PAGINATED_SEARCH")) {
            retrievedData ="GET_PAGINATED_SEARCH", queryString, start, limit);
        } else {
            retrievedData = api.retrieve();

The GET_PAGINATED is an action string we will send to the server if we want to download paginated data, but without applying a search constraint. The GET_PAGINATED_SEARCH will be sent if we want to paginate a search result. will perform a search against our database.However note that the GET_PAGINATED will search with an empty constraint, thus returning all records. Otherwise the GET_PAGINATED_SEARCH will send a search term typed the user.

api.retrieve() will perform a HTTP GET request, SELECTING all rows.

Now add the following code:

        retrievedData.enqueue(new Callback<ResponseModel>() {

We are invoking the enqueue method which will enqueue our HTTP Call. That call will be maded asynchronously. Thus we need to rely on callback methods for response.

Let’s then come and handle those responses, starting with a positive response:

            public void onResponse(Call<ResponseModel> call, Response<ResponseModel>
             response) {
                Log.d("RETROFIT", "CODE : " + response.body().getCode());
                Log.d("RETROFIT", "MESSAGE : " + response.body().getMessage());
                Log.d("RETROFIT", "RESPONSE : " + response.body().getResult());
                currentPageScientists = response.body().getResult();

                if (currentPageScientists != null && currentPageScientists.size() > 0) {
                    if (action.equalsIgnoreCase("GET_PAGINATED_SEARCH")) {
                    for (int i = 0; i < currentPageScientists.size(); i++) {

                } else {
                    if (action.equalsIgnoreCase("GET_PAGINATED_SEARCH")) {

Take a look at those parameters in our onResponse(): Call<ResponseModel> call and Response<ResponseModel> response. Clearly you see the generic type is a ResponseModel object. That ResponseModel will contain our message, our message code and our list of scientists.

That’s why we are logging them out as you you can see above.

We assign the list of scientists we have just downlaoded into the currentPageScientists arraylist. If the user was searching then we will clear the allPagesScientists. We then add the current page scientists into our allPagesScientists.

If the currentPageScientists list is empty, that is if we receive an empty list from the server, we check if the user was searching. If that is the case, then we clear allPagesScientists.Why? Well because the user has typed a search term which hits not match in the server therefore we clear our list to indicate there is no search item.

Live Video Lesson(Recommended)

Then we refresh our adapter and hide the progressbar:


Then we handle the failure response:

            public void onFailure(Call<ResponseModel> call, Throwable t) {
                Log.d("RETROFIT", "ERROR: " + t.getMessage());
                Utils.showInfoDialog(ScientistsActivity.this, "ERROR", t.getMessage());

Well that’s the end of that method.

Let’s now come and listen to recyclerview scroll events. This method will allow us implement our load more pagination. Add the following code:

     * We will listen to scroll events. This is important as we are implementing scroll to
     * load more data pagination technique
    private void listenToRecyclerViewScroll() {
        rv.addOnScrollListener(new OnScrollListener() {
            public void onScrollStateChanged(RecyclerView rv, int newState) {
                //when scrolling starts
                super.onScrollStateChanged(rv, newState);
                //check for scroll state
                if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
                    isScrolling = true;
            public void onScrolled(RecyclerView rv, int dx, int dy) {
                // When the scrolling has stopped
                super.onScrolled(rv, dx, dy);
                currentScientists = layoutManager.getChildCount();
                totalScientists = layoutManager.getItemCount();
                scrolledOutScientists = ((LinearLayoutManager) rv.getLayoutManager()).

                if (isScrolling && (currentScientists + scrolledOutScientists ==
                 totalScientists)) {
                    isScrolling = false;

                    if (dy > 0) {
                        // Scrolling up
                         String.valueOf(totalScientists), "5");

                    } else {
                        // Scrolling down

We’ve started by invoking the addOnScrollListener() method. Use this method as the setOnScrollListener has since been deprecated. We pass an annonymous class, OnScrollListener to our addOnScrollListener method.

This forces us to override or implement two methods:

  1. onScrollStateChanged() and
  2. onScrolled

The first will be raised when our scroll state changes. If the newState equals AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL), then the user is actually scrolling. Thus we set the isScrolling property to true.

The second callback method, the onScrolled() will be invoked when the scrolling has stopped. Thus we get the current page and load data for that page.

Let’s proceed.

Add the following code to finish this activity:

     * We inflate our menu. We show SearchView inside the toolbar
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(, menu);
        MenuItem searchItem = menu.findItem(;
        SearchView searchView = (SearchView) searchItem.getActionView();
        return true;

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
                Utils.openActivity(this, CRUDActivity.class);
                return true;
        return super.onOptionsItemSelected(item);

    public boolean onQueryTextSubmit(String query) {
        return false;

    public boolean onQueryTextChange(String query) {
        retrieveAndFillRecyclerView("GET_PAGINATED_SEARCH", query, "0", "5");
        return false;

    public boolean onMenuItemActionExpand(MenuItem item) {
        return false;

    public boolean onMenuItemActionCollapse(MenuItem item) {
        return false;

    protected void attachBaseContext(Context newBase) {

    public void onBackPressed() {

    protected void onCreate(Bundle savedInstanceState) {

        retrieveAndFillRecyclerView("GET_PAGINATED", "", "0", "5");


That’s it. Now move over to the next lesson.

Leave a Reply

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

WordPress › Error

The site is experiencing technical difficulties.