Android RecyclerView Pagination - Next/Previous Pagination

android pagination

Android RecyclerView Pagination - Next/Previous Pagination

In this class we see how to page/paginate data which is very important especially with RecyclerView which are meant to show large datasets.

The type of pagination we do here is the next/previous pagination. The user can navigate pages via the next/previous buttons.

If we reach the last page the next button gets disabled automatically while if we are at the first page the previous button gets disabled. In between both buttons are enabled.

Page 1

Page 2

Why Pagination?

Pagination is vital for not only ease of use by the user but also for smooth perfomance of the device. Users need permission because we human beings are not very good at processing huge data sets. It overwhelms when we have to scroll through a large list of data and identify an item out of it. Instead our brain is good ta getting the gist of things. Just a snapshot so that we have the big picture.

It's why I always encourage through my tutorials adding of search as well as pagination to lists of data. Pagination allows user to break data into chunks. Users can then view a small amount at a time. Maybe 5 or 10 items.

Pagination also improves the loading time of data. Especially when data is coming from a data source like a database or cloud solutions like firebase. This is important because the android OS is very strict with resource usages in applications. So when your app has a large data set that it' loading and this takes time, the android OS may shut down you activity due to too much memory usage. This lead to bad reputation and negative reviews in the play store and online review sites.

Paging data enables user move along the workflow quickly and efficiently.

Next/Previous Pagination

There are several pagination types like load more, 1,2,3... and endless pagination. However next/previous is the oldest of these and applies to most systems and frameworks. You basically have two buttons, one is next and the other is previous. Next allows you navigate to the next page while previous allows you navigate to previous page.

Let's go.

1. Create Basic Activity Project
  1. First create a new project in android studio. Go to File --> New Project.

Here's our project struecture.

Project Structures

2. Build.gradle

Let's come to our app level(app folder) build.gradle:


dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    testImplementation 'junit:junit:4.12'
    implementation 'com.android.support:appcompat-v7:24.2.0'
    implementation 'com.android.support:design:24.2.0'
    implementation 'com.android.support:cardview-v7:24.2.0'

}

You can see from our build.gradle that we aren't using any third party libraries. Instead we have appcompat, design and cardview support libraries. We are interested in the design support as it has the recyclerview which is the list component we use. The appcompat on the other had will give us the AppCompatActivity which is our MainActivity's super class. Our recyclerview will be showing cardviews.

3. Create User Interface

User interfaces are typically created in android using XML layouts as opposed to direct java coding.

Here are our layouts for this project:

(a). activity_main.xml
  • This layout gets inflated to MainActivity user interface.
  • It includes the content_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
    android:fitsSystemWindows="true"
    tools:context="com.tutorials.hp.recyclerpagination.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

(b). content_main.xml

This layout gets included in your activity_main.xml. We define our UI widgets here.

In this case we add a RecyclerView and two buttons(next/previous). At the root we have defined a RelativeLayout.

<?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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.tutorials.hp.recyclerpagination.MainActivity"
    tools:showIn="@layout/activity_main">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <Button
                android:text="Previous"
                android:id="@+id/prevBtn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
            <Button
                android:text="Next"
                android:id="@+id/nextBtn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </LinearLayout>

    </LinearLayout>
</RelativeLayout>

We have two LinearLayouts. The second one will render our next and previous buttons next to each other horizontally. That's why it's orientation is horizontal. The first one will place our recyclerview above the two buttons, that's why we've set the orientation to vertical.

(c). model.xml

This is the layout that defines the model of a single CardView in our RecyclerView. So we start by defining the CardView as the root view. We've given it several properties like the Card corner radius and card elevation. We have a TextView inside it. That textview will be used to render our data.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_margin="5dp"
    card_view:cardCornerRadius="5dp"
    card_view:cardElevation="2dp"
    android:layout_height="130dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Name"
            android:id="@+id/nameTxt"
            android:padding="10dp"
            android:layout_alignParentLeft="true"
             />
    </RelativeLayout>
</android.support.v7.widget.CardView>

Lets now come to classes:

4. MyViewHolder.java

This is our RecyclerView.ViewHolder class:

This class in our RecyclerView.ViewHolder class.

It derives from android.support.v7.widget.RecyclerView.View thus forcing us to create a constructor public MyHolder(View itemView) that takes a View object as a parameter and pass it over the base clas by a call to super(itemView).

Here are the roles of this class

No. Role
1. Hold a View object already inflated from XML layout for recycling. This avoids re-inflation of the same layout which is an expensive process. Thus this improves the performance of list items rendering for recyclerview. The inflated View is received via the constructor
2. Searches for individual widgets by their id from the inflated View and defines instance fields them. This ensures that those widgets can easily be retrieved as instance fields and their values set especially inside our RecyclerView.Adapter sub-class.
3. Can also be used implement onClick event listener which can be handled by other classes especially the adapter class.

Here's the ViewHolder code.

package com.tutorials.hp.recyclerpagination.mRecycler;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.tutorials.hp.recyclerpagination.R;

public class MyViewHolder extends RecyclerView.ViewHolder {

        TextView nametxt;

        public MyViewHolder(View itemView) {
            super(itemView);
            nametxt= (TextView) itemView.findViewById(R.id.nameTxt);
        }
}

4. MyAdapter.java

This is our RecyclerView.Adapter class.

This is our RecyclerView.Adapter class.

It derives from android.support.v7.widget.RecyclerView.Adapter<RecyclerView.ViewHolder myHolder> class.

Deriving from Recylcerview.Adapter will force us to either make our adapter class abstract or go ahead and override a couple of methods. We choose the latter, overriding onCreateViewHolder(ViewGroup parent, int viewType) and onBindViewHolder(MyHolder holder, final int position).

This class will adapt our data set to our RecyclerView which we use an adapterview adapterview.

Here are the main responsibilities of this class:

No. Responsibility
1. This class will be responsible for inflating our custom model layout to a View object to be used as our RecyclerView itemView.
2. A RecyclerView.ViewHolder instance will then be created with the View object passed to it. All these we do inside the onCreateVewHolder() method.
3. We'll then bind data to our view widgets inside the onBindViewHolder().
4. Handling of click events for our inflated View item.
5. Returning the total item Count to be used when rendering our view items.
package com.tutorials.hp.recyclerpagination.mRecycler;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.tutorials.hp.recyclerpagination.R;

import java.util.ArrayList;

public class MyAdapter extends RecyclerView.Adapter<MyViewHolder>  {
    Context c;
    ArrayList<String> spacecrafts;
    public MyAdapter(Context c, ArrayList<String> spacecrafts) {
        this.c = c;
        this.spacecrafts = spacecrafts;
    }

    //INITIALIZE VH
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.model,parent,false);
        return new MyViewHolder(v);
    }
    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        //BIND DATA
        holder.nametxt.setText(spacecrafts.get(position));
    }
    //TOTAL NUM
    @Override
    public int getItemCount() {
        return spacecrafts.size();
    }
}

6. Paginator.java

This is the class that will page/paginate our RecyclerView data.

package com.tutorials.hp.recyclerpagination.mPager;

import java.util.ArrayList;

public class Paginator {
    public static final int TOTAL_NUM_ITEMS=52;
    public static final int ITEMS_PER_PAGE=7;
    public static final int ITEMS_REMAINING=TOTAL_NUM_ITEMS % ITEMS_PER_PAGE;
    public static final int LAST_PAGE=TOTAL_NUM_ITEMS/ITEMS_PER_PAGE;

    public ArrayList<String> generatePage(int currentPage)
    {
        int startItem=currentPage*ITEMS_PER_PAGE+1;
        int numOfData=ITEMS_PER_PAGE;
        ArrayList<String> pageData=new ArrayList<>();

        if (currentPage==LAST_PAGE && ITEMS_REMAINING>0)
        {
            for (int i=startItem;i<startItem+ITEMS_REMAINING;i++)
            {
                pageData.add("Number "+i);
            }
        }else
        {
            for (int i=startItem;i<startItem+numOfData;i++)
            {
                pageData.add("Number "+i);
            }
        }
        return pageData;
    }
}

7. MainActivity.java

So this is our main activity. It derives from AppCompatActivity.

Here are it's major responsibilities:

No. Responsibility
1. Allow itself to become an android activity component by deriving from android.app.activity.
2. Listen to activity creation callbacks by overrding the onCreate() method.
3. Invoke the onCreate() method of the parent Activity class and tell it of a Bundle we've received.
4. Inflate the activity_main.xml into a View object and set it as the content view of this activity.
package com.tutorials.hp.recyclerpagination;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;

import com.tutorials.hp.recyclerpagination.mPager.Paginator;
import com.tutorials.hp.recyclerpagination.mRecycler.MyAdapter;

public class MainActivity extends AppCompatActivity {

    RecyclerView rv;
    Button nextBtn, prevBtn;
    Paginator p = new Paginator();
    private int totalPages = Paginator.TOTAL_NUM_ITEMS / Paginator.ITEMS_PER_PAGE;
    private int currentPage = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //RFERENCE VIEWS
        rv = (RecyclerView) findViewById(R.id.rv);
        nextBtn = (Button) findViewById(R.id.nextBtn);
        prevBtn = (Button) findViewById(R.id.prevBtn);
        prevBtn.setEnabled(false);

        //RECYCLER PROPERTIES
        rv.setLayoutManager(new LinearLayoutManager(this));

        //ADAPTER
        rv.setAdapter(new MyAdapter(MainActivity.this, p.generatePage(currentPage)));

        //NAVIGATE
        nextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                currentPage += 1;
                // enableDisableButtons();
                rv.setAdapter(new MyAdapter(MainActivity.this, p.generatePage(currentPage)));
                toggleButtons();

            }
        });
        prevBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                currentPage -= 1;

                rv.setAdapter(new MyAdapter(MainActivity.this, p.generatePage(currentPage)));

                toggleButtons();
            }
        });
    }

    private void toggleButtons() {
        if (currentPage == totalPages) {
            nextBtn.setEnabled(false);
            prevBtn.setEnabled(true);
        } else if (currentPage == 0) {
            prevBtn.setEnabled(false);
            nextBtn.setEnabled(true);
        } else if (currentPage >= 1 && currentPage <= totalPages) {
            nextBtn.setEnabled(true);
            prevBtn.setEnabled(true);
        }
    }
}

More Resources

Resource Link
GitHub Browse Browse
GitHub Download Link Download

Best Regards, Oclemy.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post