Android Studio: Fetch Data From Local Storage /SQLite(2020) in your app— PART 1 (Creating Database)

Nirvik Basnet
5 min readMay 12, 2020

Let’s get started with using SQLite for your Android App. The whole tutorial will have two parts. For this part we are just focusing on creating a database with android studio.

For this I have created a simple project with simple design to get you started:

STEP 1: Designing the UI

Create a New Project in Android Studio and follow along.

In your project go to res>layout>activity_main.xml

Inside this file we will be creating some TextViews, EditText fields and some buttons. For this part we are only creating TextViews and EditText field for Product ID and Product Name and a Save Button. You can simply copy and paste the code below in your activity_main.xml file.

<?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/editTextID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:ems="10"
android:hint="Enter product ID"
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/textViewName"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.486" />

<TextView
android:id="@+id/textViewID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="56dp"
android:layout_marginLeft="56dp"
android:text="Product ID:"
android:textSize="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.366" />

<TextView
android:id="@+id/textViewName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginLeft="32dp"
android:text="Product Name :"
android:textSize="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.484" />

<EditText
android:id="@+id/editTextName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginLeft="32dp"
android:layout_marginEnd="28dp"
android:layout_marginRight="28dp"
android:ems="10"
android:hint="Enter Product Name"
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toEndOf="@+id/textViewID"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.365" />

<Button
android:id="@+id/buttonSave"

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="232dp"
android:background="@drawable/button_selector"
android:elevation="10dp"
android:text="Save"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.479"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editTextID" />

</androidx.constraintlayout.widget.ConstraintLayout>

STEP 2: Creating DatabaseHelper Class

Now create a new package and name it database. Inside this package create a new class and name it DatabaseHelper.

Inside the DatabaseHelper class, we will have the code to create the database, create table , insert, update, delete and view methods.

At the beginning, we extend the DatabaseHelper class with SQLiteOpenHelper class. SQLiteOpenHelper class helps in the process of creating the database and managing version of the database.

After extending this class we will get some error message suggesting to implements some methods. Go ahead and implement all those methods.

This Creates two Methods onCreate() and onUpgrade(). This callbacks are invoked only when we try to open the database. onCreate() is for creating a database if it does not exists and onUpgrade() is for updating the database if the version is lower than requested by the constructor.

After this we are asked to create a constructor, let’s go ahead and do it. Select the first option.

Now, we are ready with a file with no errors.

Lets , now declare name of the database, name of the columns and version of the database along with some sql queries.

//name of the table and columns
public static final String TABLE_NAME = "products";
public static final String COLUMN_ID = "productID";
public static final String COLUMN_NAME = "productName";

//setting database name and version

public static final String DB_FILE_NAME = "products.db";
public static final int DB_VERSION = 1; // for database version

//sql statement to call create method
public static final String SQL_CREATE = "CREATE TABLE " + TABLE_NAME + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_NAME + " TEXT" + ");";
//public static final String SQL_DELETE = "DROP TABLE " + TABLE_NAME;

Now, lets make some changes in the constructor method. We will delete all other parameters and only keep the Context context. Change it to the following.


public DatabaseHelper(Context context) {

super(context, DB_FILE_NAME,null,DB_VERSION);
SQLiteDatabase db = this.getWritableDatabase();
}

Now inside the onCreate() method, we pass the SQL_CREATE statement in execSQL() method. execSQL() helps you execute SQL queries.

public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE);
}

And for the onUpgrade() method, we first delete the existing table and recreate it.

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

db.execSQL(SQL_DELETE);
onCreate(db);


}

So the whole code in DatabaseHelper, looks like this:

package com.nirvik.localstorageapp.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class DatabaseHelper extends SQLiteOpenHelper {


SQLiteDatabase db;

//naming column of table

public static final String TABLE_NAME = "products";
public static final String COLUMN_ID = "productID";
public static final String COLUMN_NAME = "productName";

//setting database name and version

public static final String DB_FILE_NAME = "products.db";
public static final int DB_VERSION = 1; // for database version

//sql statement to call create method
public static final String SQL_CREATE = "CREATE TABLE " + TABLE_NAME + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_NAME + " TEXT" + ");";
public static final String SQL_DELETE = "DROP TABLE " + TABLE_NAME;


//constructor for dbHelper
public DatabaseHelper(Context context) {

super(context, DB_FILE_NAME, null, DB_VERSION);
SQLiteDatabase db = this.getWritableDatabase();
}


//passing the create sql command
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE);
}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

db.execSQL(SQL_DELETE);
onCreate(db);


}
}

STEP 3: Invoking DatabaseHelper constructor in MainActivity to create database.

package com.nirvik.localstorageapp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.nirvik.localstorageapp.database.DatabaseHelper;

public class MainActivity extends AppCompatActivity {



DatabaseHelper myDB; //Creating instance

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



myDB = new DatabaseHelper(this); //invoking the constructer







}
}

STEP 4: Checking if the database is created or not.

Run the android project and check the data inside the Device File Explorer. Which is in the bottom right corner of android studio.

Click data>data> find your app (with package name)

In my case, my package is com.nirvik.localstorageapp and when I expand it I can see a database folder with database name I declared that is products.db.

In next part we will learn how to add , delete, update and view items inside the database from the app.

--

--