Android SQLite → Android SQLite – RecyclerView – Infinite/Endless Pagination,Load More [ServerSide] – Camposha

Android SQLite

Android SQLite

Android SQLite

Android SQLite – RecyclerView – Infinite/Endless Pagination,Load More [ServerSide]

 

Android SQLite – RecyclerView – Infinite/Endless Pagination,Load More [ServerSide] Tutorial.

How to page/paginate data from SQLite and in RecyclerView using he Load More technique.

 

In this tutorial we continue looking at the SQlite Pagination. How to page/paginate data endlessly. We use the Load More technique. The user scrolls the RecyclerView,when he reaches the end of the list,we load more data from SQlite database.

We are performing our SQlite pagination at the server side. While loading our data using the endless scroll,we shall be displaying a ProgressBar as the data loads. Our RecyclerView comprises cardviews.

We first insert/save data into SQlite database via a dialog, then select the data and bind to our RecyclerView. We also see how to swipe/pull to refresh our data.

If you pull down.swipe down our recyclerView,we refresh our dataset and take us back to the first page of our data.We are suing the pullLoadView library.Here’s what we do in short :

  • First Insert/Save data to SQlite database from a dialog with edittexts.
  • If the app is run,it tries to select/retrieve the first page of our dataset.
  • The first page comprises 5 items each displayed in a cardView.
  • We eager load the second page when you are in the first page.
  • When you scroll to the second page,we eager load the third page,then fourth when you are in the third page and so on.
  • While laoding more data,we show a progress bar at the bottom of our RecyclerView.
  • SQlite is fast compared to loading of data from a server. We shall load the data in the background thread using handlers.Now we are going to show our progressbar for three seconds even though our SQlite queries of fetching the five items in a page will be much faster than the 3 seconds.The purpose is to teach infinite scroll,so the three seconds shall make our progressbar visible and simulate a real world fetching of data from the server. Take note though that we are fetching data from an actual database in SQLite.
  • We are using RushORM for our SQLite database stuff.RushORM is a relational object mapper an shall map our model class into sqlite table without us writing sql statements.Moreover,our queries we shall perform in Java not SQL.

Project Demo

Our Gradle Scripts

There are two build.gradle files in our android studio project :

(a). Build.Gradle (Project)

This is Our project level build.gradle, here we add the repository url for our RushORM.We fetch it from maven.

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        maven {
            url "http://maven.rushorm.com"
        }
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
(b). Build.Gradle (App)
  • Here we add some of the dependencies we shallbe using,including third part dependencies.
  • RushORM and PullLoadVeiw are third party libraries.
  • RushORM is for our SQlite database while PullLoadView enables us implement Pull to Load More in our RecyclerView.
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support:design:24.2.1'
    compile 'com.android.support:cardview-v7:24.2.1'
    compile 'co.uk.rushorm:rushandroid:1.2.0'
    compile 'com.github.tosslife:pullloadview:1.1.0'
}

Our Layouts

(a). ContentMain.xml
  • Our Activity’s Content Layout.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    
    
    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.sqliteinfinitepager.MainActivity"
    tools_showIn="@layout/activity_main">

    <com.srx.widget.PullToLoadView
    android_id="@+id/pullToLoadView"
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    />
</RelativeLayout>
(b). Model.xml
  • Our model layout.
  • We inflate this to our RecyclerView viewitems.
  • At the root we have a CardView.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView 
    android_orientation="horizontal" android_layout_width="match_parent"
    
    android_layout_margin="10dp"
    card_view_cardCornerRadius="10dp"
    card_view_cardElevation="10dp"
    android_layout_height="200dp">

    <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>
(c). DialogLayout.xml
  • We are performing SQLite CRUD,so we need an input dialog with edittext and button.
<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.CardView 
    android_orientation="horizontal" android_layout_width="500dp"
    
    android_layout_margin="1dp"
    card_view_cardCornerRadius="10dp"
    card_view_cardElevation="5dp"
    android_layout_height="match_parent">

    <LinearLayout
        android_layout_width="match_parent"
        android_orientation="vertical"
        android_layout_height="match_parent">

        <android.support.design.widget.TextInputLayout
            android_id="@+id/nameLayout"
            android_layout_width="match_parent"
            android_layout_height="wrap_content">

            <EditText
                android_id="@+id/nameEditTxt"
                android_layout_width="match_parent"
                android_layout_height="wrap_content"
                android_singleLine="true"
                android_hint= "Name" />
        </android.support.design.widget.TextInputLayout>

        <Button android_id="@+id/saveBtn"
            android_layout_width="fill_parent"
            android_layout_height="wrap_content"
            android_text="Save"
            android_clickable="true"
            android_background="@color/colorAccent"
            android_layout_marginTop="40dp"
            android_textColor="@android:color/white"/>

    </LinearLayout>

</android.support.v7.widget.CardView>

Our Classes

We have a total of 5 classes :

(a). MainApplication
  • Extends our Application class.
  • Given its global,we take advantage and initialize our RushORM here.
package com.tutorials.hp.sqliteinfinitepager;

import android.app.Application;

import co.uk.rushorm.android.AndroidInitializeConfig;
import co.uk.rushorm.core.RushCore;

public class MainApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        //INITIALIZE RUSHCORE CONFIGURATION
        AndroidInitializeConfig config=new AndroidInitializeConfig(getApplicationContext());
        RushCore.initialize(config);
    }
}
(b). Spaceship
  • Is our model class, to represent a spaceship with properties like name.
  • We’ll map it to RushORM by supplying an empty constructor and deriving from RushObject.
package com.tutorials.hp.sqliteinfinitepager.mData;

import co.uk.rushorm.core.RushObject;

public class Spaceship extends RushObject {
    private String name;

    public Spaceship() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
(c). MyAdapter
  • To adapt our dataset to the corresponding views.
  • We inflate our Model.xml layout here.
  • We also have an inner viewholder class.
package com.tutorials.hp.sqliteinfinitepager.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.TextView;

import com.tutorials.hp.sqliteinfinitepager.R;
import com.tutorials.hp.sqliteinfinitepager.mData.Spaceship;

import java.util.List;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyHolder> {

    Context c;
    List<Spaceship> spaceships;

    /*
    CONSTRUCTOR
     */
    public MyAdapter(Context c, List<Spaceship> spaceships) {
        this.c = c;
        this.spaceships = spaceships;
    }

    //INITIALIE VH
    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.model, parent, false);
        MyHolder holder = new MyHolder(v);
        return holder;
    }

    //BIND DATA
    @Override
    public void onBindViewHolder(MyHolder holder, int position) {
        holder.nametxt.setText(spaceships.get(position).getName());

    }

    /*
    TOTAL ITEMS
     */
    @Override
    public int getItemCount() {
        return spaceships.size();

    }

    /*
    ADD DATA TO ADAPTER
     */
    public void add(Spaceship s) {
        spaceships.add(s);
        notifyDataSetChanged();
    }

    /*
    CLEAR DATA FROM ADAPTER
     */
    public void clear() {
        spaceships.clear();
        notifyDataSetChanged();
    }

    /*
    VIEW HOLDER CLASS
     */
    class MyHolder extends RecyclerView.ViewHolder {

        TextView nametxt;

        public MyHolder(View itemView) {
            super(itemView);

            this.nametxt = (TextView) itemView.findViewById(R.id.nameTxt);

        }
    }

}
(d). Paginator
  • This class shall page for us our SQLite data.
  • This is where we retrieve our SQlite data.We said we are performing server side pagination.
  • With RushORM we can use the limit() and offset() methods to set our limit and offset values.
  • We then set itour RecyclerView’s adapter.
(f). MainActivity
  • Our launcher activity.
  • We show initialize our dialog here and show it when user clicks the Floating Action Button.
  • WE then save to SQlite database with help of RushORM when user clicks the save button from edittext.
  • We initialize our PullLoadView here and use it to obtain a RecyclerView.

AndroidManiefst.xml

  • Given that we are using RusORM,lets complete our setup.You need to add metadata that RushORM shall use to¬† know you datavse meta information like database name.
  • But the most important thing is to make sure you specify the path to your model class by specifying the package name in the Rush_classes_package meta.For instance our model class is Spaceship so we add the package of our spaceship class.e.g
  • Also regisetr you MainApplication by specifying the name in our <application>tag. e. g

android:name=".MainApplication".

Screenshot

Leave a Reply

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

Price

Free

Rating

Not enough ratings to display
X