Android SQLite Database in Kotlin
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.
SQLiteOpenHelper class
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.
Constructor | Description |
---|---|
SQLiteOpenHelper(context: Context, name: String, factory: SQLiteDatabase.CursorFactory, version: Int) | Creates an object of SQLiteOpenHelper for creating, opening and managing the database. |
SQLiteOpenHelper(context: Context, name: String, factory: SQLiteDatabase.CursorFactory, version: Int, errorHandler: DatabaseErrorHandler) | Creates an object of SQLiteOpenHelper for creating, opening and managing the database. It specifies the error handler. |
Step By Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio
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.
- XML
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
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.
- Kotlin
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.
- Kotlin
Now run your app and see the output.
Post a Comment
0Comments