Home Android SQlite : RecyclerView -CRUD then Swipe/Pull To Refresh

Android SQlite : RecyclerView -CRUD then Swipe/Pull To Refresh

Android SQlite : RecyclerView -CRUD then Swipe/Pull To Refresh




Good morning/afternoon/evening guys.Today we continue with our SQlite Database series of tutorial.Episode 10.We talk about how to implement Swipe To Refresh in our RecyclerView with SQLite database.Of course we start from scratch,so we shall tackle inserting and selecting and ofcourse creating our table.
In short this is what we do in this episode 10:

1.INSERT data to SQLite database.
2.SELECT data from our SQLite database.
3.Reload/Refresh data from our SQLite database when the user swipes/pulls down our RecyclerView.We are using SwipeRefreshLayout introduced in Android KitKat.

 

First we shall start by defining our Constants class.This is the class that shall house all our SQLite database constants :

 

package com.tutorials.hp.sqliteswipetorefresh.mDataBase;

/**
 * Created by Oclemmy on 5/2/2016 for ProgrammingWizards Channel and http://www.Camposha.com.
 */
public class Constants {
    //COLUMNS
    static final String ROW_ID="id";
    static final String NAME="name";

    //DB PROPS
    static final String DB_NAME="hh_DB";
    static final String TB_NAME="hh_TB";
    static final int DB_VERSION=1;


    //CREATE_TB
    static final String CREATE_TB="CREATE TABLE hh_TB(id INTEGER PRIMARY KEY AUTOINCREMENT,"
            + "name TEXT NOT NULL);";


    //DROP_TB
     static final String DROP_TB="DROP TABLE IF EXISTS "+TB_NAME;


}

 

We also have a DBHelper class as well as DBAdapter class.The DBHelper shall upgrade our database table as well as create it.You can find it in the source code.It derives from SQLiteOpenHeper.

Then the DBAdapter class shall handle our CRUD :

 

package com.tutorials.hp.sqliteswipetorefresh.mDataBase;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

/**
 * Created by Oclemmy on 5/2/2016 for ProgrammingWizards Channel and http://www.Camposha.com.
 */
public class DBAdapter {

    Context c;
    SQLiteDatabase db;
    DBHelper helper;

    public DBAdapter(Context c) {
        this.c = c;
        helper=new DBHelper(c);
    }

    //OPEN DB
    public void openDB()
    {
        try
        {
            db=helper.getWritableDatabase();
        }catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    //CLOSING
    public void closeDB()
    {
        try
        {
            helper.close();

        }catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    //SAVE OR INSERTING
    public boolean add(String name)
    {
        try
        {
            ContentValues cv=new ContentValues();
            cv.put(Constants.NAME, name);

            db.insert(Constants.TB_NAME, Constants.ROW_ID, cv);

            return true;

        }catch (SQLException e)
        {
            e.printStackTrace();
        }

        return false;
    }

    //SELECT OR RETRIEVE
    public Cursor retrieve()
    {
        String[] columns={Constants.ROW_ID,Constants.NAME};

        return db.query(Constants.TB_NAME,columns,null,null,null,null,null);
    }
}

 

 

Here's our RecyclerView adapter class to bind our database data to RecyclerView.Furthermore we shall listen swipes using SwipeRefreshListener and hence fetch updates from the SQlite database.

 

package com.tutorials.hp.sqliteswipetorefresh.mRecycler;

import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.tutorials.hp.sqliteswipetorefresh.R;
import com.tutorials.hp.sqliteswipetorefresh.mDataBase.DBAdapter;
import com.tutorials.hp.sqliteswipetorefresh.mDataObject.SpaceCraft;

import java.util.ArrayList;

/**
 * Created by Oclemmy on 5/2/2016 for ProgrammingWizards Channel and http://www.Camposha.com.
 */
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {

    Context c;
    ArrayList<SpaceCraft> spaceCrafts;
    SwipeRefreshLayout swipeRefreshLayout;

    public MyAdapter(Context c, ArrayList<SpaceCraft> spaceCrafts, SwipeRefreshLayout swipeRefreshLayout) {
        this.c = c;
        this.spaceCrafts = spaceCrafts;
        this.swipeRefreshLayout = swipeRefreshLayout;
    }

    @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;
    }

    @Override
    public void onBindViewHolder(MyHolder holder, int position) {
        holder.nameTxt.setText(spaceCrafts.get(position).getName());

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getUpdates();
            }
        });

    }

    @Override
    public int getItemCount() {
        return spaceCrafts.size();
    }

    private void getUpdates()
    {
        spaceCrafts.clear();

        DBAdapter db=new DBAdapter(c);
        db.openDB();
        Cursor c=db.retrieve();

        while (c.moveToNext())
        {
            int id=c.getInt(0);
            String name=c.getString(1);

            SpaceCraft s=new SpaceCraft();
            s.setId(id);
            s.setName(name);

            spaceCrafts.add(s);
        }

        db.closeDB();

        swipeRefreshLayout.setRefreshing(false);
        this.notifyDataSetChanged();
    }
}

 

Finally our MainActivity is right below :

 

package com.tutorials.hp.sqliteswipetorefresh;

import android.app.Dialog;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
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.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


import com.tutorials.hp.sqliteswipetorefresh.mDataBase.DBAdapter;
import com.tutorials.hp.sqliteswipetorefresh.mDataObject.SpaceCraft;
import com.tutorials.hp.sqliteswipetorefresh.mRecycler.MyAdapter;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    RecyclerView rv;
    MyAdapter adapter;
    SwipeRefreshLayout swipeRefreshLayout;
    EditText nameEditText;
    Button saveBtn,retrieveBtn;
    ArrayList<SpaceCraft> spaceCrafts=new ArrayList<>();

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

        rv= (RecyclerView) findViewById(R.id.rv);
        rv.setLayoutManager(new LinearLayoutManager(this));

        swipeRefreshLayout= (SwipeRefreshLayout) findViewById(R.id.swiper);

        adapter=new MyAdapter(this,spaceCrafts,swipeRefreshLayout);


        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                displayDialog();
            }
        });



    }

    private void displayDialog()
    {
        Dialog d=new Dialog(this);
        d.setTitle("Save To Database");
        d.setContentView(R.layout.dialog_layout);

        nameEditText= (EditText) d.findViewById(R.id.nameEditTxt);
        saveBtn= (Button) d.findViewById(R.id.saveBtn);
        retrieveBtn= (Button) d.findViewById(R.id.retrieveBtn);

        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save(nameEditText.getText().toString());

            }
        });
        retrieveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 getSpaceCrafts();
            }
        });

        d.show();
    }

    private void save(String name)
    {
        DBAdapter db=new DBAdapter(this);
        db.openDB();
        if(db.add(name))
        {
            nameEditText.setText("");
        }else {
            Toast.makeText(this,"Unable to save",Toast.LENGTH_SHORT).show();
        }

        db.closeDB();
    }

    private void getSpaceCrafts()
    {
        spaceCrafts.clear();

        DBAdapter db=new DBAdapter(this);
        db.openDB();
        Cursor c=db.retrieve();

        while (c.moveToNext())
        {
            int id=c.getInt(0);
            String name=c.getString(1);

            SpaceCraft s=new SpaceCraft();
            s.setId(id);
            s.setName(name);

            spaceCrafts.add(s);
        }

        db.closeDB();

        rv.setAdapter(adapter);
    }


}
















 

By the way the full source code reference is above for download.Just download it,extract and import to your android studio.

 

 
The Youtube video tutorial is below.Its explained in a step by step fashion and you can also view the project demo over there.

 

    Leave a Reply

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

    one × two =

    Leave a Comment

    8 − 4 =