Display data from database asset folder to RecyclerView – Android Studio

In this post, we discussed how to import data from a database and display it in recycler view in android studio.

Start with 1st Step:

Create a new Activity after creation create a new asset folder and place the database file in it.

2nd Step:

Place (database file).DB folder in assets folder.

3rd Step:

  • Create a Recycler View, adapter, and layout
  • For recycler view tutorial, click here

4th Step:

  1. We have to create a class of database helper by which we can create, check, copy and open database functionalities
  2. We can assign a database string etc as shown below
  3. Start with Main Activity
  4. In Mainactivity.xml we set recycler view and in Mainactivity.java we have set adapter for recycler view and database helper class

MainActivity XML:

<?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"
    tools:context=".MainActivity">


<androidx.recyclerview.widget.RecyclerView
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:id="@+id/recyclerview"/>

</RelativeLayout>


MainActivity Java:

package com.example.db;

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.database.SQLException;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.io.IOException;
import java.util.ArrayList;

public class MainActivity extends  AppCompatActivity {

    Cursor c = null;

    ArrayList<String> id, name, cname, currency, language, area, details;

    RecyclerView recyclerView;
    
    CustomAdapter customAdapter;

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

        recyclerView = findViewById(R.id.recyclerview);

        DatabaseHelper myDbHelper = new DatabaseHelper(MainActivity.this);
        id = new ArrayList<>();
        name = new ArrayList<>();
        cname = new ArrayList<>();
        currency = new ArrayList<>();
        language = new ArrayList<>();
        area = new ArrayList<>();
        details = new ArrayList<>();

        customAdapter = new CustomAdapter(MainActivity.this, this, id, name, cname,
                currency, language, area, details);
        recyclerView.setAdapter(customAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));


        try {
            myDbHelper.createDataBase();
        } catch (IOException ioe) {
            throw new Error("Unable to create database");
        }
        try {
            myDbHelper.openDataBase();
        } catch (SQLException sqle) {
            throw sqle;
        }
//                Toast.makeText(MainActivity.this, "Successfully Imported", Toast.LENGTH_SHORT).show();
        c = myDbHelper.query("Country", null, null, null, null, null, null);
        if (c.moveToFirst()) {
            do {
                id.add(c.getString(0));
                name.add(c.getString(1));
                cname.add(c.getString(2));
                currency.add(c.getString(3));
                language.add(c.getString(4));
                area.add(c.getString(5));
                details.add(c.getString(6));


            } while (c.moveToNext());
        }
    }
}

Layout:

  • This is the layout for recycler view which is used to be call in adapter
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"

    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="15dp"
    android:id="@+id/mainLayout">

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="2dp">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="12dp">

            <TextView
                android:id="@+id/book_id_txt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="1"
                android:textSize="20sp"
                android:textStyle="bold"
                android:textColor="#000"
                android:layout_marginLeft="15dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@+id/book_title_txt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginLeft="16dp"
                android:text="Title 1"
                android:textSize="20sp"
                android:textStyle="bold"
                android:textColor="#000"
                app:layout_constraintStart_toEndOf="@+id/book_id_txt"
                app:layout_constraintTop_toTopOf="@+id/book_id_txt" />

            <TextView
                android:id="@+id/book_author_txt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Author1"
                app:layout_constraintStart_toStartOf="@+id/book_title_txt"
                app:layout_constraintTop_toBottomOf="@+id/book_title_txt" />

            <TextView
                android:id="@+id/book_pages_txt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="120"
                android:textSize="18sp"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@+id/book_city_txt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="120"
                android:textSize="18sp"
                android:visibility="invisible"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@+id/book_area_txt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="120"
                android:textSize="18sp"
                android:visibility="invisible"
                app:layout_constraintEnd_toEndOf="@+id/book_city_txt"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@+id/book_details_txt"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="120"
                android:textSize="18sp"
                android:visibility="invisible"
                app:layout_constraintEnd_toEndOf="@+id/book_city_txt"
                app:layout_constraintTop_toTopOf="parent" />

        </androidx.constraintlayout.widget.ConstraintLayout>
    </androidx.cardview.widget.CardView>
</LinearLayout>

Adapter for recyclerview:

package com.example.db;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {

    private Context context;
    private Activity activity;
    ArrayList<String> id, name, cname, currency, language, area, details;

    CustomAdapter(Activity activity, Context context, ArrayList id, ArrayList name, ArrayList cname,
                  ArrayList currency, ArrayList language, ArrayList area,ArrayList details){

        this.activity = activity;
        this.context = context;
        this.id = id;
        this.name = name;
        this.cname = cname;
        this.currency = currency;
        this.language = language;
        this.area = area;
        this.details = details;
    }

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

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {
        holder.cid.setText(String.valueOf(id.get(position)));
        holder.cnm.setText(String.valueOf(name.get(position)));
        holder.ccnm.setText(String.valueOf(cname.get(position)));
        holder.ccr.setText(String.valueOf(currency.get(position)));
Bonus if you want click on recyclerview to get data from database 
then use that part other wise run the code 
        //Recyclerview onClickListener
        holder.mainLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, display.class);
                intent.putExtra("id", String.valueOf(id.get(position)));
                intent.putExtra("name", String.valueOf(name.get(position)));
                intent.putExtra("cname", String.valueOf(cname.get(position)));
                intent.putExtra("currency", String.valueOf(currency.get(position)));
                intent.putExtra("language", String.valueOf(language.get(position)));
                intent.putExtra("area", String.valueOf(area.get(position)));
                intent.putExtra("details", String.valueOf(details.get(position)));
                activity.startActivityForResult(intent, 1);
            }
        });


    }

    @Override
    public int getItemCount() {

        return id.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        TextView cid, cnm, ccnm, ccr, clng, carea, cdtls;
        LinearLayout mainLayout;

        MyViewHolder(@NonNull View itemView) {

            super(itemView);
            cid = itemView.findViewById(R.id.book_id_txt);
            cnm = itemView.findViewById(R.id.book_title_txt);
            ccnm = itemView.findViewById(R.id.book_author_txt);
            ccr = itemView.findViewById(R.id.book_pages_txt);
            clng =itemView.findViewById(R.id.book_city_txt);
            carea=itemView.findViewById(R.id.book_area_txt);
            cdtls=itemView.findViewById(R.id.book_details_txt);
            mainLayout = itemView.findViewById(R.id.mainLayout);

        }

    }

}

DatabaseHelper class.java:

package com.example.db;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class DatabaseHelper extends SQLiteOpenHelper {

    String DB_PATH = null;
    private static String DB_NAME = "Countries.db";
    private SQLiteDatabase myDataBase;
    private final Context myContext;

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, 10);
        this.myContext = context;
        this.DB_PATH = "/data/data/" + context.getPackageName() + "/" + "databases/";
        Log.e("Path 1", DB_PATH);
    }


    public void createDataBase() throws IOException {
        boolean dbExist = checkDataBase();
        if (dbExist) {
        } else {
            this.getReadableDatabase();
            try {
                copyDataBase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    private boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        try {
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
        } catch (SQLiteException e) {
        }
        if (checkDB != null) {
            checkDB.close();
        }
        return checkDB != null ? true : false;
    }

    private void copyDataBase() throws IOException {
        InputStream myInput = myContext.getAssets().open(DB_NAME);
        String outFileName = DB_PATH + DB_NAME;
        OutputStream myOutput = new FileOutputStream(outFileName);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

    public void openDataBase() throws SQLException {
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }

    @Override
    public synchronized void close() {
        if (myDataBase != null)
            myDataBase.close();
        super.close();
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (newVersion > oldVersion)
            try {
                copyDataBase();
            } catch (IOException e) {
                e.printStackTrace();

            }
    }

    public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) {
        return myDataBase.query("Country", null, null, null, null, null, null);
    }


}

Display layout on click on recycler view:
Display.XML:

<?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:layout_marginBottom="10dp"
    tools:context=".display">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp">

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/teal_700"
        android:textColor="@color/black"
        android:textSize="30dp"
        android:layout_marginTop="16dp"
        android:textAlignment="center"
        android:text="@string/app_name"
        android:gravity="center_horizontal" />

    <TextView
        android:id="@+id/cname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:textColor="@color/black"
        android:layout_below="@id/name"
        android:textSize="20dp"
        android:text="@string/app_name" />

    <TextView

        android:id="@+id/currency"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:textColor="@color/black"
        android:textSize="20dp"
        android:inputType="number"
        android:layout_below="@+id/cname" />

    <TextView

        android:id="@+id/language"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:textColor="@color/black"
        android:textSize="19dp"
        android:layout_below="@id/currency"
        android:text="@string/app_name" />

    <TextView

        android:id="@+id/area"
        android:layout_marginTop="16dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/language"
        android:textColor="@color/black"
        android:textSize="19dp"
        android:textStyle="bold"
        android:text="@string/app_name"

        />

    <TextView

        android:id="@+id/details"
        android:layout_marginTop="16dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/area"

        android:textColor="@color/black"
        android:textSize="25dp"
        android:text="@string/app_name"
        android:layout_marginBottom="20dp"

        />

    </RelativeLayout>
    </ScrollView>

</RelativeLayout>

Display.java:

package com.example.db;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class display extends AppCompatActivity {
    String name, cname, area, language, currency, details, id;
    TextView nme,cnme,curency,lnguage,are,detail;

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

        nme = findViewById(R.id.name);
        cnme = findViewById(R.id.cname);
        curency = findViewById(R.id.currency);
        lnguage = findViewById(R.id.language);
        are = findViewById(R.id.area);
        detail = findViewById(R.id.details);


        getAndSetIntentData();


    }

    private void getAndSetIntentData() {
//        if (getIntent().hasExtra("id") && getIntent().hasExtra("name") &&
//                getIntent().hasExtra("cname") && getIntent().hasExtra("currency") && getIntent().hasExtra("language")
//                && getIntent().hasExtra("area")
//                && getIntent().hasExtra("details")) {

//            Getting Data from Intent
            id = getIntent().getStringExtra("id");
            name = getIntent().getStringExtra("name");
            cname = getIntent().getStringExtra("cname");
            currency = getIntent().getStringExtra("currency");
            language = getIntent().getStringExtra("language");
            area = getIntent().getStringExtra("area");
            details = getIntent().getStringExtra("details");

            //Setting Intent Data
            nme.setText( name);
            cnme.setText("Capital:      "+cname);
            curency.setText("Currency:       "+currency);
            lnguage.setText("Languages:        "+language);
            are.setText("AREA:       "+area);
            detail.setText("Details:       "+details);
            Log.d("stev", name + " " + cname + "  " + currency + " " + language + " " + area + " " + details);
        }
//        else {
//            Toast.makeText(this, "No Data to Show", Toast.LENGTH_SHORT).show();
//        }

    }