Android SQLite Database in Kotlin (original) (raw)
Last Updated : 23 Jul, 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 `
<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: