Android Academy · Lesson

The Room Database Class

Create and access your database.

Lesson 2 of 413 steps

The Room Database Class is a free Android Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Android Academy learning path, and your progress syncs across the web and the CoddyKit app. The Android Academy course includes 4 lessons in total.

Tying It Together

The database class is the main access point. It lists your entities, declares the version, and exposes your DAOs.

The @Database Annotation

Create an abstract class extending RoomDatabase and annotate it with @Database.

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

@Database(
    entities = [User::class],
    version = 1
)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
}

Listing Entities and Version

The entities array tells Room which tables to create. The version number tracks schema changes for migrations.

Exposing DAOs

For each DAO, declare an abstract function returning that DAO type. Room implements it.

abstract fun userDao(): UserDao
abstract fun noteDao(): NoteDao

Building the Database

Use Room.databaseBuilder to create an instance. It needs an application context, the class, and a database name.

val db = Room.databaseBuilder(
    context.applicationContext,
    AppDatabase::class.java,
    "app.db"
).build()

Make It a Singleton

Creating a database is expensive, so create one instance for the whole app. A common pattern uses a companion object with a synchronized getter.

companion object {
    @Volatile private var INSTANCE: AppDatabase? = null
    fun get(context: Context): AppDatabase =
        INSTANCE ?: synchronized(this) {
            INSTANCE ?: build(context).also { INSTANCE = it }
        }
}

Why a Singleton Matters

Multiple database instances would open multiple connections to the same file, causing inconsistency and wasted memory. One shared instance keeps a single source of truth.

Providing It with Hilt

In real apps you usually provide the database through dependency injection (covered in the Hilt course) instead of a manual singleton.

@Provides
@Singleton
fun provideDb(@ApplicationContext ctx: Context) =
    Room.databaseBuilder(ctx, AppDatabase::class.java, "app.db")
        .build()

Schema Changes and Migrations

When you change an entity, increment the version and supply a Migration describing the SQL to transform old data.

val MIGRATION_1_2 = object : Migration(1, 2) {
    override fun migrate(db: SupportSQLiteDatabase) {
        db.execSQL("ALTER TABLE users ADD COLUMN age INTEGER NOT NULL DEFAULT 0")
    }
}

Destructive Migration

During early development you may use fallbackToDestructiveMigration(), which drops and recreates tables instead of migrating. Never ship this to production with real user data.

Accessing DAOs

Once you have the database instance, get a DAO and call its methods inside a coroutine.

val dao = db.userDao()
viewModelScope.launch {
    dao.insert(User(1, "Ada", "ada@x.com"))
}

Quick Check

Test your understanding of the database class.

Recap

You learned:

  • @Database lists entities, sets a version, and exposes DAOs.
  • Build it with Room.databaseBuilder as a singleton.
  • Schema changes need an incremented version and a Migration.
Free to start

Learn Kotlin with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
36
Lessons
152

Frequently Asked Questions

Is the “The Room Database Class” lesson free?

Yes — any 3 lessons of the Android Academy learning path, including “The Room Database Class”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Android Academy course includes 4 lessons in total.

What will I learn in “The Room Database Class”?

Create and access your database. You practise Android Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Android Academy?

No prior experience is required. Android Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.

How long does the “The Room Database Class” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Android Academy lesson?

Yes. Every Android Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Entities and DAOs
  2. The Room Database Class
  3. Queries and Relationships
  4. Observing Data with Flow
← Back to Android Academy