0Pricing
Android Academy · Lesson

Room Database

Persist structured data locally with Room. Define Entities, DAOs, and the Database class. Query with SQL and observe results with LiveData or Flow.

Room Database is a free Android Academy lesson on CoddyKit — lesson 2 of 6. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Android Academy learning path, one of 6 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is Room?

Room is Google's recommended persistence library for Android. It's a wrapper around SQLite that gives you:

  • Type-safe SQL queries verified at compile time
  • Kotlin coroutine support
  • LiveData / Flow integration
  • Migration support for schema changes

Room's Three Components

Room is built from three annotations:

  • @Entity — a data class that maps to a database table
  • @Dao (Data Access Object) — an interface with SQL queries
  • @Database — the main database class that ties everything together

Adding Room Dependencies

Add Room to app/build.gradle:

// app/build.gradle
plugins {
    id 'kotlin-kapt'  // needed for Room annotation processor
}

dependencies {
    val roomVersion = "2.6.1"
    implementation "androidx.room:room-runtime:$roomVersion"
    kapt "androidx.room:room-compiler:$roomVersion"
    implementation "androidx.room:room-ktx:$roomVersion" // coroutine support
}

Defining an Entity

Annotate a data class with @Entity to create a database table:

import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity(tableName = "notes")
data class Note(
    @PrimaryKey(autoGenerate = true)
    val id: Int = 0,
    val title: String,
    val body: String,
    val createdAt: Long = System.currentTimeMillis()
)

// Each field = one column in the database table
// @PrimaryKey autoGenerate = Room assigns the id automatically

Creating the DAO

Define queries in a DAO interface. Room generates the implementation for you:

import androidx.room.*
import kotlinx.coroutines.flow.Flow

@Dao
interface NoteDao {

    @Query("SELECT * FROM notes ORDER BY createdAt DESC")
    fun getAllNotes(): Flow<List<Note>>  // emits new list whenever data changes

    @Query("SELECT * FROM notes WHERE id = :noteId")
    suspend fun getNoteById(noteId: Int): Note?

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(note: Note)

    @Update
    suspend fun update(note: Note)

    @Delete
    suspend fun delete(note: Note)
}

Creating the Database

The @Database class is the entry point to Room. Build it once and keep it as a singleton:

import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import android.content.Context

@Database(entities = [Note::class], version = 1, exportSchema = false)
abstract class NoteDatabase : RoomDatabase() {

    abstract fun noteDao(): NoteDao

    companion object {
        @Volatile private var INSTANCE: NoteDatabase? = null

        fun getInstance(context: Context): NoteDatabase {
            return INSTANCE ?: synchronized(this) {
                Room.databaseBuilder(
                    context.applicationContext,
                    NoteDatabase::class.java,
                    "note_database"
                ).build().also { INSTANCE = it }
            }
        }
    }
}

Using Room in ViewModel

Wire up the DAO in a ViewModel using coroutines:

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch

class NoteViewModel(private val dao: NoteDao) : ViewModel() {

    val notes = dao.getAllNotes()  // Flow — auto-updates when DB changes

    fun addNote(title: String, body: String) {
        viewModelScope.launch {
            dao.insert(Note(title = title, body = body))
        }
    }

    fun deleteNote(note: Note) {
        viewModelScope.launch {
            dao.delete(note)
        }
    }
}

Observing Room Data in UI

Collect the Flow from Room in your Activity or Fragment:

import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch

class NoteActivity : AppCompatActivity() {
    private val viewModel: NoteViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // ...

        lifecycleScope.launch {
            viewModel.notes.collect { notes ->
                adapter.submitList(notes)  // update RecyclerView
            }
        }
    }
}

Database Migrations

When you change your Entity (add a column, rename a table), you must provide a migration so existing user data isn't lost.

Increment the version number in @Database(version = 2) and define a Migration object with the SQL to transform the old schema to the new one.

Quick Check

Which Room annotation marks an interface method as a SQL SELECT query?

Recap: Room Database

You can now build apps with local data persistence:

  • @Entity — data class → database table
  • @Dao — interface with @Query, @Insert, @Delete
  • @Database — singleton entry point
  • Return Flow<List> from DAO for live updates
  • Call DAO from ViewModel using viewModelScope.launch

Next: write async code without callbacks using Coroutines.

Frequently asked questions

Is the “Room Database” lesson free?

Yes — the full text of “Room Database” is free to read here on the web, and the Android Academy course includes 6 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Android Academy course, upgrade to CoddyKit PRO.

What will I learn in “Room Database”?

Persist structured data locally with Room. Define Entities, DAOs, and the Database class. Query with SQL and observe results with LiveData or Flow. 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; this is — lesson 2 of 6, so you can start here or from the beginning and move at your own pace.

How long does the “Room Database” 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. ViewModel & LiveData
  2. Room Database
  3. Coroutines & Suspend Functions
  4. Repository Pattern
  5. Navigation Component
  6. Dependency Injection with Hilt
← Back to Android Academy