Display SQLite Data in RecyclerView | Android SQLite with Recycler view example | NP-X Coding


SQLite Database is one of the best and interesting topics in Android development. In this article, you will learn to Display SQLite Data in RecyclerView with a simple example.

If you don't know how to implement SQLite with Android and if you want to know how to insert data in the SQLite database then here is the complete information to store data in the SQLite database in android.

In this article, we will create a simple app that will display SQLite data in Recyclerview.


Create your XML layout

First, create your activity layout and add a Recyclerview in your activity layout.


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">

    <EditText
        android:id="@+id/edittext1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="add item"
        android:inputType="textPersonName"
        android:textColor="#000000"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.278"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.976" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ADD"
        android:textColor="#000000"
        app:backgroundTint="#FFFFFF"
        app:layout_constraintBottom_toBottomOf="@+id/edittext1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/edittext1"
        app:layout_constraintTop_toTopOf="@+id/edittext1" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclearview"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/edittext1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>


Database


Database.java

package com.example.recyclearview;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;

public class Database extends SQLiteOpenHelper {

    private Context context;
    private static final String DATABASE_NAME = "database1.db";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = "User_data";
    private static final String COLUMN_ID = "id";
    private static final String NAME = "name";

    public Database(@Nullable Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context=context;
    }

    
    @Override
    public void onCreate(SQLiteDatabase db) {
        //create table
        String query = "  CREATE TABLE  " + TABLE_NAME + " ( " + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT , " + NAME + " TEXT);";
        db.execSQL(query);
    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(" DROP TABLE IF EXISTS "+TABLE_NAME);
    }

    //for insert data in table
    void insert(String name)
    {
        SQLiteDatabase db=this.getWritableDatabase();
        ContentValues cv=new ContentValues();
        cv.put(NAME,name);
        db.insert(TABLE_NAME,null,cv);
    }

    //return all inserted data in form of cursor
    Cursor readAllData(){
        String query="SELECT * FROM "+TABLE_NAME+" ";
        SQLiteDatabase db=getReadableDatabase();
        Cursor cur1=null;
        if(db!=null) {
            cur1=db.rawQuery(query,null);//rawQuery returns a set of rows and columns in a Cursor.
        }
        return cur1;
    }
} 


Code Explanation : 


1. Create Database

Now Create a database class. Initialize fields and in the oncreate() method, execute a query for creating a table. and also don't forget to generate a constructor.

2. Insert method for inserting data in the table.

Create a method named "insert". basically, this method is for inserting data in the database, we will call this method in our activity on insert button click. 

3. readAllData method for retrieve table data

"readAllData"  - this method is returning all data which are inserted into the database table. this is the main method for retrieving and displaying SQLite data in Recyclerview.


Recyclerview Item layout

We have to create a new layout file for the design recycler view item because later we will need this layout in the Adapter class. you can design your recycler view item as your requirement.

To create a new layout resource file do the following :

  1. Right-click on the " res folder
  2. Select new
  3. Select Android Resource File
  4. Give a specific name to the file and press ok

item_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/item_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#FFFFFF">

    <TextView
        android:id="@+id/item_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:text="TextView"
        android:textSize="20sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>


Adapter

Now it's time to implement the RecyclerView. If you don't know how to use the RecyclerView, then you can learn it from here.

If you are familiar with RecyclerView, you know that the adapter class stands for bind data with views in RecyclerView. So just create an Adapter class in your project as shown below.

Adapter.java

package com.example.recyclearview;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;

public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
    @NonNull
    private Context context;
    private ArrayList<String> item_text;

    public Adapter(@NonNull Context context, ArrayList<String> item_text) {
        this.context = context;
        this.item_text = item_text;
    }

    @Override
    public Adapter.MyViewHolder onCreateViewHolder(@NonNull  ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater=LayoutInflater.from(context);
        View view=layoutInflater.inflate(R.layout.item_layout,parent,false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull  Adapter.MyViewHolder holder, int position) {
        holder.item_textview.setText(item_text.get(position));
    }

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

    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView item_textview;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            item_textview=itemView.findViewById(R.id.item_textview);
        }
    }
}


MainActivity


MainActivity.java

package com.example.recyclearview;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    EditText editText;
    Button button;
    ArrayList<String> items;
    Adapter adapter;
    RecyclerView recyclerView;
    Database database;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText=findViewById(R.id.edittext1);
        button=findViewById(R.id.button);
        recyclerView=findViewById(R.id.recyclearview);
        items=new ArrayList<>();
        database=new Database(MainActivity.this);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                database.insert(editText.getText().toString().trim());
                startActivity(new Intent(MainActivity.this,MainActivity.class));
            }
        });
        store_Data_In_Array();
        adapter=new Adapter(MainActivity.this,items);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
    }

    void store_Data_In_Array() {

        Cursor cursor = database.readAllData();
        while (cursor.moveToNext()) {
//            column 0 is id in table
//            column 1 is name in table
            items.add(cursor.getString(1));
        }
    }
}

Code Explanation :


  • RecyclerView setup

Open your MainActivity.java file and initialize views. Create an object of the Adapter class and set the Adapter object to RecyclerView. don't forget to set layout manager with RecyclerView. Now, the recycler view setup is completed.

  • Initialization of ArrayList

In the MainActivity.java, ArrayList is empty  So we have to initialize ArrayList with all inserted data in the database table. 

Create a method named "store_Data_In_Array"  as shown in codeBasically, this method will receive all SQLite data which are retrieved by the "readAllData"  method, and then all those data will be initialized to ArrayList.


Output


So as you can see, when the user clicks on the insert button, the Edit text value is stored in the SQLite table. and then those data are displayed to recycler view.

This is the best and easiest way to Display SQLite Data in RecyclerView in android.

Share this article with your friends and support NP-X Coding for more quality content. You can also follow us on Instagram for coding tips and learning.