Kotlin Android SQLite Tutorial
SQLite is an open-source relational database that is used to perform database operations on Android devices such as storing, manipulating or retrieving persistent data from the database.
By default SQLite database is embedded in android. So, there is no need to perform any database setup or administration task.
The SQLiteOpenHelper class provides the functionality to use the SQLite database.
The android.database.sqlite.SQLiteOpenHelper class is used for database creation and version management. For performing any database operation, you have to provide the implementation of onCreate() and onUpgrade() methods of SQLiteOpenHelper class.
Constructors of SQLiteOpenHelper class
There are two constructors of SQLiteOpenHelper class.
Methods of SQLiteOpenHelper class
There are several methods available in the SQLiteOpenHelper class. Some of them are mentioned below:
It contains methods to be performed on the SQLite database such as create, update, delete, select etc.
Methods of SQLiteDatabase class
There are many methods in the SQLiteDatabase class. Some of them are as follows:
Kotlin Android SQLite Database CRUD Example
In this example, we will perform create, read, update and delete operation on Android SQLite database.
In the activity_main.xml file add the following code. In this file, we added three EditText, one ListView, four Button for saving, view, update and delete operation.
Add the following code in the MainActivity.kt class. In this class, the saveRecord() function saves the records. The viewRecord() function reads the record and displays them into ListView, the updateRecord() function updates the record on the basis on id, and deleteRecord() function deletes the record. The val databaseHandler: DatabaseHandler= DatabaseHandler(this) creates the instance of DatabaseHandler class calls the SQLite database logic.
Creating a data model class named as EmpModelClass.kt
Create a custom row layout for displaying the list items in the ListView.
Now, create a custom adapter class named as MyListAdapter.kt and extends ArrayAdapter class which populates the data model into the ListView.
Create a layout for display AlertDialog for update record.
Create a layout for display AlertDialog for delete record.
Create the DatabaseHandler.kt class that extends SQLiteOpenHelper class and override its onCreate(), onUpgrage() functions. Insert data into the database by passing a ContentValues object to the insert() method.