Android comes with an inbuilt implementation of a database package, which is SQLite, an open-source SQL database that stores data in form of text in devices. In this article, we will look at the implementation of Android SQLite in Kotlin.
SQLite is a self-contained, high-reliability, embedded, full-featured, public-domain, SQL database engine. It is the most used database engine in the world. It is an in-process library and its code is publicly available. It is free for use for any purpose, commercial or private. It is basically an embedded SQL database engine. Ordinary disk files can be easily read and write by SQLite because it does not have any separate server like SQL. The SQLite database file format is cross-platform so that anyone can easily copy a database between 32-bit and 64-bit systems. Due to all these features, it is a popular choice as an Application File Format.
What are we going to build in this article?
We will be building a simple application that will be storing data using SQLite and we will also implement methods to retrieve the data. Below is a sample video to show what we will be doing.
Step By Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Giving permission to access the storage in the AndroidManifest.xml file
Navigate to app > AndroidManifest.xml and add the below code to it.
< uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE" />
|
Step 3: Working with the activity_main.xml file
Navigate to app > res > layout > activity_main.xml. Add the below code to your file. Below is the code for activity_main.xml.
<? xml version = "1.0" encoding = "utf-8" ?>
< LinearLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:orientation = "vertical"
tools:context = ".MainActivity" >
<!-- Edit text to enter name -->
< EditText
android:id = "@+id/enterName"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:hint = "Enter Name"
android:textSize = "22sp"
android:layout_margin = "20sp" />
<!-- Edit text to enter age -->
< EditText
android:id = "@+id/enterAge"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_margin = "20sp"
android:textSize = "22sp"
android:hint = "Enter Age" />
<!-- Button to add Name -->
< Button
android:id = "@+id/addName"
android:layout_width = "150sp"
android:layout_gravity = "center"
android:background = "@color/colorPrimary"
android:text = "Add Name"
android:textColor = "#ffffff"
android:textSize = "20sp"
android:layout_height = "wrap_content"
android:layout_marginTop = "20sp" />
<!-- Button to print Name -->
< Button
android:id = "@+id/printName"
android:layout_width = "150sp"
android:layout_gravity = "center"
android:background = "@color/colorPrimary"
android:text = "Print Name"
android:textColor = "#ffffff"
android:textSize = "20sp"
android:layout_height = "wrap_content"
android:layout_marginTop = "20sp" />
< LinearLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content" >
<!-- Text view to get all name -->
< TextView
android:id = "@+id/Name"
android:textAlignment = "center"
android:layout_weight = "1"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_margin = "20sp"
android:text = "Name\n\n"
android:textSize = "22sp"
android:padding = "10sp"
android:textColor = "#000000" />
<!-- Text view to get all ages -->
< TextView
android:layout_weight = "1"
android:id = "@+id/Age"
android:textAlignment = "center"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_margin = "20sp"
android:text = "Age\n\n"
android:textSize = "22sp"
android:padding = "10sp"
android:textColor = "#000000" />
</ LinearLayout >
</ LinearLayout >
|
Step 4: Creating a new class for SQLite operations
Navigate to app > java > your project’s package name > Right-click on it > New > Kotlin class and name it as DBHelper and add the below code to it. To make the code more understandable, comments are added.
package com.release.gfg1
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class DBHelper(context: Context, factory: SQLiteDatabase.CursorFactory?) :
SQLiteOpenHelper(context, DATABASE_NAME, factory, DATABASE_VERSION) {
// below is the method for creating a database by a sqlite query
override fun onCreate(db: SQLiteDatabase) {
// below is a sqlite query, where column names
// along with their data types is given
val query = ( "CREATE TABLE " + TABLE_NAME + " ("
+ ID_COL + " INTEGER PRIMARY KEY, " +
NAME_COl + " TEXT," +
AGE_COL + " TEXT" + ")" )
// we are calling sqlite
// method for executing our query
db.execSQL(query)
}
override fun onUpgrade(db: SQLiteDatabase, p1: Int, p2: Int) {
// this method is to check if table already exists
db.execSQL( "DROP TABLE IF EXISTS " + TABLE_NAME)
onCreate(db)
}
// This method is for adding data in our database
fun addName(name : String, age : String ){
// below we are creating
// a content values variable
val values = ContentValues()
// we are inserting our values
// in the form of key-value pair
values.put(NAME_COl, name)
values.put(AGE_COL, age)
// here we are creating a
// writable variable of
// our database as we want to
// insert value in our database
val db = this .writableDatabase
// all values are inserted into database
db.insert(TABLE_NAME, null , values)
// at last we are
// closing our database
db.close()
}
// below method is to get
// all data from our database
fun getName(): Cursor? {
// here we are creating a readable
// variable of our database
// as we want to read value from it
val db = this .readableDatabase
// below code returns a cursor to
// read data from the database
return db.rawQuery( "SELECT * FROM " + TABLE_NAME, null )
}
companion object{
// here we have defined variables for our database
// below is variable for database name
private val DATABASE_NAME = "GEEKS_FOR_GEEKS"
// below is the variable for database version
private val DATABASE_VERSION = 1
// below is the variable for table name
val TABLE_NAME = "gfg_table"
// below is the variable for id column
val ID_COL = "id"
// below is the variable for name column
val NAME_COl = "name"
// below is the variable for age column
val AGE_COL = "age"
}
} |
Step 5: Working with MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
package com.release.gfg1
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super .onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// below code is to add on click
// listener to our add name button
addName.setOnClickListener{
// below we have created
// a new DBHelper class,
// and passed context to it
val db = DBHelper( this , null )
// creating variables for values
// in name and age edit texts
val name = enterName.text.toString()
val age = enterAge.text.toString()
// calling method to add
// name to our database
db.addName(name, age)
// Toast to message on the screen
Toast.makeText( this , name + " added to database" , Toast.LENGTH_LONG).show()
// at last, clearing edit texts
enterName.text.clear()
enterAge.text.clear()
}
// below code is to add on click
// listener to our print name button
printName.setOnClickListener{
// creating a DBHelper class
// and passing context to it
val db = DBHelper( this , null )
// below is the variable for cursor
// we have called method to get
// all names from our database
// and add to name text view
val cursor = db.getName()
// moving the cursor to first position and
// appending value in the text view
cursor!!.moveToFirst()
Name.append(cursor.getString(cursor.getColumnIndex(DBHelper.NAME_COl)) + "\n" )
Age.append(cursor.getString(cursor.getColumnIndex(DBHelper.AGE_COL)) + "\n" )
// moving our cursor to next
// position and appending values
while (cursor.moveToNext()){
Name.append(cursor.getString(cursor.getColumnIndex(DBHelper.NAME_COl)) + "\n" )
Age.append(cursor.getString(cursor.getColumnIndex(DBHelper.AGE_COL)) + "\n" )
}
// at last we close our cursor
cursor.close()
}
}
} |
Now run your app and see the output.
Output: