How to use a simple SQLite database in Kotlin android?

This example demonstrates how to use a simple SQLite database in Kotlin android.
Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?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"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context=".MainActivity">
   <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical">
   <EditText
      android:id="@+id/editTextName"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_margin="10dp"
      android:padding="8dp" />
   <EditText
      android:id="@+id/editTextAge"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_margin="10dp"
      android:autofillHints="Age"
      android:inputType="number"
      android:padding="8dp"
      android:textColor="@android:color/background_dark" />
   <Button
      android:id="@+id/btnInsert"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_margin="10dp"
      android:padding="8dp"
      android:text="Add data" />
   </LinearLayout>
   <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:gravity="center"
      android:orientation="horizontal"
      android:weightSum="3">
   <Button
      android:id="@+id/btnRead"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_margin="10dp"
      android:layout_weight="1"
      android:padding="8dp"
      android:text="Read" />
   </LinearLayout>
   <ScrollView
      android:layout_width="match_parent"
      android:layout_height="match_parent>
   <TextView
      android:id="@+id/tvResult"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:padding="8dp"
      android:textSize="16sp"
      android:textStyle="bold" />
   </ScrollView>
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.kt
package app.com.q10
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)
      title = "KotlinApp"
      val context = this
      val db = DataBaseHandler(context)
      btnInsert.setOnClickListener {
         if (editTextName.text.toString().isNotEmpty() &&
            editTextAge.text.toString().isNotEmpty()
         ) {
            val user = User(editTextName.text.toString(), editTextAge.text.toString().toInt())
            db.insertData(user)
            clearField()
         }
         else {
            Toast.makeText(context, "Please Fill All Data's", Toast.LENGTH_SHORT).show()
         }
      }
      btnRead.setOnClickListener {
         val data = db.readData()
         tvResult.text = ""
         for (i in 0 until data.size) {
            tvResult.append(
               data[i].id.toString() + " " + data[i].name + " " + data[i].age + "\n"
            )
         }
      }
   }
   private fun clearField() {
      editTextName.text.clear()
      editTextAge.text.clear()
   }
}
Step 4 − Add the following code to src/DataBaseHelper.kt
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.widget.Toast
val DATABASENAME = "MY DATABASE"
val TABLENAME = "Users"
val COL_NAME = "name"
val COL_AGE = "age"
val COL_ID = "id"
class DataBaseHandler(var context: Context) : SQLiteOpenHelper(context, DATABASENAME, null,
1) {
   override fun onCreate(db: SQLiteDatabase?) {
      val createTable = "CREATE TABLE " + TABLENAME + " (" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_NAME + " VARCHAR(256)," + COL_AGE + " INTEGER)"
      db?.execSQL(createTable)
   }
   override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
      //onCreate(db);
   }
   fun insertData(user: User) {
      val database = this.writableDatabase
      val contentValues = ContentValues()
      contentValues.put(COL_NAME, user.name)
      contentValues.put(COL_AGE, user.age)
      val result = database.insert(TABLENAME, null, contentValues)
      if (result == (0).toLong()) {
         Toast.makeText(context, "Failed", Toast.LENGTH_SHORT).show()
      }
      else {
         Toast.makeText(context, "Success", Toast.LENGTH_SHORT).show()
      }
   }
   fun readData(): MutableList<User> {
      val list: MutableList<User> = ArrayList()
      val db = this.readableDatabase
      val query = "Select * from $TABLENAME"
      val result = db.rawQuery(query, null)
      if (result.moveToFirst()) {
         do {
            val user = User()
            user.id = result.getString(result.getColumnIndex(COL_ID)).toInt()
            user.name = result.getString(result.getColumnIndex(COL_NAME))
            user.age = result.getString(result.getColumnIndex(COL_AGE)).toInt()
            list.add(user)
         }
         while (result.moveToNext())
      }
      return list
   }
}
Step 5 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.kotlipapp">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.