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.
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. Below is a sample video to show what we will be doing.
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: Giving permission to access the storage in the AndroidManifest.xml file
Navigate to app > AndroidManifest.xml and add the below code to it.
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.
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.
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.
Now run your app and see the output.