How to Use Room Database with Hilt in Jetpack Compose?

Emine İNAN
Huawei Developers
Published in
4 min readJun 27, 2024
Photo by NASA on Unsplash

Introduction 🌟

In the Android app development process, properly handling dependency management and database operations is crucial for the sustainability and maintainability of the project. Hilt plays a significant role in simplifying dependency injection, while the Room streamlines and secures database management. In this article, we will explore how to use Room Database with Hilt in Jetpack Compose.

What is Hilt?

Hilt is an Android dependency injection library that simplifies manual dependency injection by managing the construction and lifecycle of dependencies. By using Hilt, developers can reduce boilerplate code and make their applications more modular and testable.

What is Room?

Room is a persistence library that is part of Android Jetpack and serves as an abstraction layer on top of an SQLite database. Instead of using SQLite directly, Room simplifies database setup, configuration, and interactions with the app, while also providing compile-time checks of SQLite statements.

Room Integration with Hilt

Integrating Hilt with Room involves several steps, including setting up the necessary dependencies, configuring Hilt modules, and creating the Room database and DAO classes. In the following section, we will go through these steps.

Sample App

Let’s explain the integration of Hilt and Room Database with Jetpack Compose by creating a simple example app called QuoteApp.

QuoteApp

Step 1

🚩 Create a new Android project with Kotlin DSL in Android Studio and add the necessary dependencies for Hilt, Room, and ViewModel.

Note: We will use version catalogs to declare dependencies. You can check here to get information about version catalogs. Gradle version catalogs simplify managing dependencies and plugins across multiple modules by centralizing their definitions.

libs. versions.toml
build.gradle.kts (Project)
build.gradle.kts (App)

Step 2

🚩 Initialize Hilt in Application class.

Annotating the Application class with @HiltAndroidApp sets up Hilt for dependency injection in your application. This is necessary to allow Hilt to generate the required components.

MainApplication.kt

Step 3

🚩 Add the MainApplication class to the AndroidManidest.xml file to configure Hilt properly.

AndroidManifest.xml

Step 4

🚩 Create an entity class called Quote for the Room database.

The Quote class is an entity representing a table in the Room database. Each instance of Quote will be a row in the quotes table. The @Entity annotation specifies this class as an entity and @PrimaryKey marks id as the primary key.

Quote.kt

Step 5

🚩 Define the DAO interface.

A DAO (Data Access Object) defines database interaction methods. The @Dao annotation identifies it as a DAO class for Room. The getAll() method uses a SQL query to retrieve all quotes, returning a Flow that allows observing changes in the data. The addQuote and deleteQuote methods handle inserting and deleting Quote objects in the database.

QuoteDao.kt

Step 6

🚩 Create the abstract QuoteDatabase class.

The QuoteDatabase class defines the Room database configuration. The @Database annotation includes the entities and the database version. The class extends RoomDatabase, and it contains an abstract method that returns the DAO.

QuoteDatabase.kt

Step 7

🚩 Provide the database and DAO instances.

This Hilt module provides the Room database and DAO instances. The @Module annotation identifies it as a Hilt module, and @InstallIn(SingletonComponent::class) indicates that the bindings are available in the singleton component. The provideAppDatabase method creates the Room database, while provideQuoteDao provides the DAO instance.

DatabaseModule.kt

Step 8

🚩 Define a sealed class named Result to represent the states of data.

The Result sealed class is used to represent different states of a data request: success, loading, and error. This helps in managing the UI state based on the data request status.

Result.kt

Step 9

🚩 Create the repository class.

The QuoteRepository class uses the DAO to interact with the database and returns data wrapped in a Result to represent different states. The repository is annotated with @Inject to enable dependency injection using Hilt.

QuoteRepository.kt

Step 10

🚩 Define the use cases for adding, deleting, and retrieving quotes.

Use cases define business logic in a centralized and reusable way, managing access to data sources through repository classes.

GetQuotesUseCase.kt
AddQuotesUseCase.kt
DeleteQuoteUseCase.kt

Step 11

Define the QuoteUiState sealed class to represent UI states.

QuoteUiState.kt

Step 12

🚩 Create a ViewModel that uses the use cases for database operations.

QuoteViewmodel.kt

Step 13

🚩 Create a composable called QuoteScreen for interacting with quotes.

QuoteScreen provides the user interface for entering quotes via a TextField, listing the quotes through a LazyColumn, and adding quotes via a Button. Quotes can be added, deleted, and listed. The user interface updates accordingly based on the quotes’ loading, success, or error states, making the UI code modular and understandable while managing data processing and user interactions.

QuoteScreen.kt

Step 14

🚩 Add the @AndroidEntryPoint annotation to the MainActivity class to enable dependency injection by Hilt and call the QuoteScreen() composable function to provide the user interface required to interact with quotes.

MainActivity.kt

Conclusion

Integrating Hilt with Room in Android app development offers a streamlined approach to dependency injection and database management. This integration enhances code maintainability, scalability, and testability by reducing boilerplate code and providing type-safe interactions with the database. By leveraging Hilt for dependency injection and Room for database operations, developers can build robust and sustainable apps with ease.

--

--

Emine İNAN
Huawei Developers

Android Developer by day, Android Developer by night. @Huawei