Introduction
Room Database is an essential topic in Android Development, enabling developers to store and manage data efficiently. It acts as an abstraction layer over SQLite, simplifying database operations and making data management more developer-friendly. In this article, we will explore Room Database step by step, with practical examples to help you understand its implementation.
Why to use Room Database
- Abstraction Layer: Room provides an abstraction layer over SQLite, allowing developers to write simpler and more idiomatic Kotlin code.
- Compile-Time Verification: Room validates queries and schema definitions at compile time, reducing runtime errors and enhancing reliability.
Key Concepts/Terminologies
- Entities: Represents table in your Database.
- Dao (Data Access Object): Defines the operations with the Database.
- Database: Acts as the database holder and contains all the tables.
Step-by-Step Implementation.
Let’s walk through the implementation process using an example of a User Database.
Step 1: Add Plugin
To get started, you need to add a plugin—either kapt or ksp. This plugin will help the compiler to understand the quotations that we will use.
-
ksp
(Kotlin Symbol Processing): Faster and more efficient for annotation processing. -
kapt
(Kotlin Android Processing Tool): Traditional and widely used.
You can choose either ksp or kapt.
If you want to learn about ksp and kapt then you can refer to the official documentation. For now, you can continue.
In this example, we will use kapt
.
- Adding
Kapt
Open your build.gradle.kts
(module level) and add the following line inside plugins
block:
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.jetbrains.kotlin.android)
id("kotlin-kapt") // Add this line
}
- Adding
ksp
Open build.gradle.kts (project level) in you project files. Here you have to add plugin for ksp.
plugins {
//other plugins...
//Your to add this. The version should be same as your kotlin (for first).
//For eg. you have kotlin version 1.9.22 then the version for ksp plugin should be 1.9.22-x.x.x
id("com.google.devtools.ksp") version "1.9.22-1.0.17" apply false
}
Now, open you build.gradle.kts (module level) add this line in plugins
block:
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.jetbrains.kotlin.android)
id("com.google.devtools.ksp") // Add this line
}
Sync your project after adding the plugin.
Step 2: Add Dependencies
Add the required dependencies for Room in your build.gradle.kts
(module level) file:
dependencies{
implementation("androidx.room:room-runtime:2.6.1")
//For Kotlin extension coroutines for room.
implementation("androidx.room:room-ktx:2.6.1")
//To use kotlin annotation processor.
kapt("androidx.room:room-compiler:2.6.1")
}
Ensure you use the latest versions of these dependencies. After adding these dependencies, sync your project.
Step 3: Creating your First Table/Entity
Create the First Table inside the Database. To create one, define a data class annotate it with @Entity
and give a name. Each entity must have at least one primary key annotate by @PrimaryKey
, you can set it to auto-generate so it will get generated automatically.
@Entity(tableName="user_table")
data class User(
@PrimaryKey(autoGenerate = true) val id:Int, //Define a primary key in table
val name:String,
val contact:Long
)
Step 4: Define a DAO Interface
DAO (Data Object Interface) defines the operations you can perform on the database such as:
- Insert
- Delete
- Query
- Update
Create an interface annotate it by @Dao
and give it a name (UserDao, in this case).
@Dao
interface UserDao {
@Insert //Define more methods as per your use
suspend fun insert(user: User)
//we can write any SQL query.
@Query("select * from user_table order by id ASC")
fun getData(): Flow<List<User>>
}
Here, getAllUsers() retrieves all users from the user_table in ascending order.
Step 5: Define a Database
Now, we will implement a database. Create an abstract class that will implement RoomDataBase()
. Annotate it by @Database
inside the annotation you will have to give all the Table/Entity names you are using and a version (we will update this version if we want to update anything in our database).
example:
@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
Step 6: Initializing Room
Finally, initialize the Room database in your application. Use the Room.databaseBuilder() method to create an instance.
val db=Room.databaseBuilder(
context,
AppDatabase::class.java, //We have to give our database class (abstract class in step 5)
"app_database" //you can give any name to database.
).build()
val userDao=db.userDao()//It is our dao.
Conclusion
In this article, we explored the fundamentals of Room Database, including adding plugins, dependencies, entities, DAOs, and initializing the database. In the next article, we will learn how to perform operations such as adding and retrieving data from the database.
Stay tuned for more practical insights into Android Development!
Top comments (0)