Save User State

Sep 10 2024 · Kotlin 1.9, Android 14, Android Studio Koala | 2024.1.1

Lesson 04: Define a Room Database

Demo

Episode complete

Play next episode

Next
Transcript

Now, you’ll learn how to define a Room Database for your notes.

To use Room in your project, you need to add the Room dependencies. Room uses annotation processors to generate code at compile time. Because of this, you need to add the Room dependencies. You also need to add the Kotlin Symbol Processing (KSP) plugin to your project. Beginning with the KSP plugin, open the project-level build.gradle file. Add the KSP plugin below the Kotlinx Serialization plugin:

id 'com.google.devtools.ksp' version '1.9.23-1.0.20' apply false

Next, add the KSP plugin to your app module’s build.gradle file:

id 'com.google.devtools.ksp'

Also in the build.gradle file, add the following dependencies. These will go inside the dependencies block:

implementation "androidx.room:room-ktx:2.6.1"
ksp "androidx.room:room-compiler:2.6.1"

Here, you add the Room dependencies and the annotation processor is used to generate code at compile time. Tap Sync Now at the top-right corner of your IDE to sync the project and add the plugin and dependency to your project.

Next, create a new file named DevScribeDatabase.kt in the data/local package. Inside this file, add the following code:

import androidx.room.Database
import androidx.room.RoomDatabase

@Database(version = 1)
abstract class DevScribeDatabase: RoomDatabase() {
}

In the above code, you define a Room database by creating an abstract class that extends the RoomDatabase class. You use the @Database annotation to define the database version. You’ll add the entities and the DAOs later on.

With this, your database class is ready. You’ll need to create an instance of your database class. You’ll create the instance inside the Koin modules so that you can provide it as a dependency to the classes that need to do database operations. Open the Module.kt file in the di package and add the room database module below the notesFileManagerModule:

val roomDatabaseModule = module {
  single {
    Room.databaseBuilder(androidContext(), DevScribeDatabase::class.java, "dev_scribe_db")
      .build()
  }
}

Remember to import the required Room and DevScribeDatabase dependencies.

In the code above, you use the Room.databaseBuilder() function to create an instance of the DevScribeDatabase class. The function takes three parameters- the context, your database class, and the database name. The build() function is used to build the database instance. Remember to add the roomDatabaseModule to the appModules list so it can be included in your Koin dependency graph.

If you run your app now, you’ll get an error because you haven’t added the entities and the DAOs to your database. You’ll do that in the next lesson.

See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion