Save User State

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

Lesson 05: Set up a Room Database

Demo: Creating DAOs

Episode complete

Play next episode

Next
Transcript

In this section, you’ll learn how to create DAOs for your Room database.

Inside the data/local package, create a new Kotlin interface. Select Kotlin Class/File and then select Interface. Name the interface NotesDao.kt. Add the following code to the file:

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import kotlinx.coroutines.flow.Flow

@Dao
interface NotesDao {
  @Insert(onConflict = OnConflictStrategy.REPLACE)
  suspend fun insert(note: NoteEntity)

  @Query("SELECT * FROM Notes")
  fun getNotes(): Flow<List<NoteEntity>>
}

In the code above, you define a NotesDao interface and annotate it with the @Dao annotation. This annotation tells Room that this interface is a Room DAO. Inside your DAO, you define two functions: insert and getNotes. The insert function inserts a new note into the database. You annotate the insert() function with the @Insert annotation. Also, you set the onConflict parameter to OnConflictStrategy.REPLACE. This tells Room to replace the note if it already exists in the database or if there’s a conflict.

Also in the code above, the suspend keyword is used to make the function a suspend function since you’re inserting data into the database. The getNotes function retrieves all notes from the database. You annotate the getNotes() function with the @Query annotation and pass the SQL query to select all notes from the Notes table. The function returns a Flow of a list of NoteEntity objects. The Flow type is used to observe changes in the database and emit new values when the data changes.

Next, you need to add the NoteDao interface to your DevScribeDatabase class. Open the DevScribeDatabase class and add the following code inside the class:

abstract fun notesDao(): NotesDao

Here, you define an abstract function notesDao() that returns a NotesDao object. This function is used to get an instance of the NotesDao interface. You’ll use this instance to interact with the database.

Lastly, you need to update your Koin modules so that you can provide an instance of the NotesDao interface. Open the Module.kt file in the di package and add the following code to the roomDatabaseModule below the database instance:

single { get<DevScribeDatabase>().notesDao() }

This provides an instance of your NotesDao interface that you can use to interact with the database.

Build and run your app. The app successfully compiles and runs, but you still can’t read or write any data to your database. You haven’t wired up your ‘NotesDao’ interface to your UI yet. You’ll learn how to do this in the next lesson.

See forum comments
Cinema mode Download course materials from Github
Previous: Introduction to Data Access Objects Next: Conclusion