Android SQLite Database in Kotlin
Last Updated :
07 Apr, 2025
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.
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: Working with 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.
activity_main.xml:
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"
android:gravity="center"
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:layout_margin="32dp"
android:hint="Enter Name"
android:inputType="textPersonName"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- Edit text to enter age -->
<EditText
android:id="@+id/enterAge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="32dp"
android:hint="Enter Age"
android:inputType="number"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="@+id/enterName"
app:layout_constraintStart_toStartOf="@+id/enterName"
app:layout_constraintTop_toBottomOf="@+id/enterName" />
<!-- Button to add Name -->
<Button
android:id="@+id/addName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="32dp"
android:text="Add Name"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="@+id/enterAge"
app:layout_constraintStart_toStartOf="@+id/enterAge"
app:layout_constraintTop_toBottomOf="@+id/enterAge" />
<!-- Button to print Name -->
<Button
android:id="@+id/printName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="32dp"
android:text="Print Name"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="@+id/addName"
app:layout_constraintStart_toStartOf="@+id/addName"
app:layout_constraintTop_toBottomOf="@+id/addName" />
<TextView
android:id="@+id/nameTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="Name"
android:textSize="24sp"
app:layout_constraintEnd_toStartOf="@+id/ageTV"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/printName" />
<TextView
android:id="@+id/ageTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Age"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="@+id/nameTV"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/nameTV"
app:layout_constraintTop_toTopOf="@+id/nameTV" />
<com.google.android.material.divider.MaterialDivider
android:id="@+id/materialDivider"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="32dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/nameTV" />
<!-- Text view to get all name -->
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:textAlignment="center"
android:textSize="24sp"
app:layout_constraintEnd_toStartOf="@+id/age"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/materialDivider" />
<!-- Text view to get all ages -->
<TextView
android:id="@+id/age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAlignment="center"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="@+id/name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/name"
app:layout_constraintTop_toTopOf="@+id/name" />
</androidx.constraintlayout.widget.ConstraintLayout>
Design UI:
Step 3: Creating a new class for SQLite operations
Navigate to app > kotlin+java > {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.
DBHelper.kt:
Kotlin
package org.geeksforgeeks.demo
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) {
// Called when the database is created for the first time
override fun onCreate(db: SQLiteDatabase) {
val createTableQuery = """
CREATE TABLE $TABLE_NAME (
$ID_COL INTEGER PRIMARY KEY AUTOINCREMENT,
$NAME_COL TEXT,
$AGE_COL TEXT
)
""".trimIndent()
db.execSQL(createTableQuery)
}
// Called when the database needs to be upgraded
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
db.execSQL("DROP TABLE IF EXISTS $TABLE_NAME")
onCreate(db)
}
// Inserts a new record into the database
fun addName(name: String, age: String) {
val values = ContentValues().apply {
put(NAME_COL, name)
put(AGE_COL, age)
}
writableDatabase.use { db ->
db.insert(TABLE_NAME, null, values)
}
}
// Retrieves all records from the database
fun getName(): Cursor {
return readableDatabase.rawQuery("SELECT * FROM $TABLE_NAME", null)
}
companion object {
private const val DATABASE_NAME = "GEEKS_FOR_GEEKS"
private const val DATABASE_VERSION = 1
const val TABLE_NAME = "gfg_table"
const val ID_COL = "id"
const val NAME_COL = "name"
const val AGE_COL = "age"
}
}
Step 4: 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.
MainActivity.kt:
Kotlin
package org.geeksforgeeks.demo
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private lateinit var addName: Button
private lateinit var printName: Button
private lateinit var enterName: EditText
private lateinit var enterAge: EditText
private lateinit var name: TextView
private lateinit var age: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Initialize UI components
addName = findViewById(R.id.addName)
printName = findViewById(R.id.printName)
enterName = findViewById(R.id.enterName)
enterAge = findViewById(R.id.enterAge)
name = findViewById(R.id.name)
age = findViewById(R.id.age)
// Create database helper instance
val db = DBHelper(this, null)
// Add data to database on button click
addName.setOnClickListener {
val inputName = enterName.text.toString().trim()
val inputAge = enterAge.text.toString().trim()
if (inputName.isEmpty() || inputAge.isEmpty()) {
// Show message if fields are empty
Toast.makeText(this, "Please enter both name and age", Toast.LENGTH_SHORT).show()
} else {
// Add name and age to database
db.addName(inputName, inputAge)
Toast.makeText(this, "$inputName added to database", Toast.LENGTH_LONG).show()
// Clear input fields
enterName.text.clear()
enterAge.text.clear()
}
}
// Retrieve and display data from database on button click
printName.setOnClickListener {
name.text = ""
age.text = ""
val cursor = db.getName()
cursor.use {
if (cursor.moveToFirst()) {
do {
val personName = cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.NAME_COL))
val personAge = cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.AGE_COL))
// Append data to text views
name.append("$personName\n")
age.append("$personAge\n")
} while (cursor.moveToNext())
}
}
}
}
}
Output:
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response
In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network
Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
3-Phase Inverter
An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is Vacuum Circuit Breaker?
A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read
What is a Neural Network?
Neural networks are machine learning models that mimic the complex functions of the human brain. These models consist of interconnected nodes or neurons that process data, learn patterns, and enable tasks such as pattern recognition and decision-making.In this article, we will explore the fundamenta
14 min read