Room Database with Hilt in Kotlin: A Guide to Store and Access Data in Android

Reza Ramesh
4 min readJul 13, 2023

--

Room is a library that provides an abstraction layer over SQLite to allow for more robust database access while harnessing the full power of SQLite. Room simplifies the creation and management of local databases in your app, and allows you to easily define your database schema, perform queries, and observe changes in data.

Hilt is a dependency injection library for Android that reduces the boilerplate of doing manual dependency injection in your project. Hilt provides a standard way to use dependency injection in your app by providing containers for every Android class in your project and managing their lifecycles automatically.

In this article, we will see how to use Room database with Hilt in Kotlin to store and access data in your Android app. We will follow these steps:

  • Add the Room and Hilt dependencies to your project’s build.gradle files.
  • Define your data entities as classes annotated with @Entity.
  • Create a DAO (Data Access Object) interface annotated with @Dao that defines the methods to access your data.
  • Create a database class that extends RoomDatabase and is annotated with @Database and @HiltAndroidApp.
  • Create a repository class that provides an abstraction layer over your data sources and is annotated with @Inject.
  • Create a view model class that exposes the data to the UI and is annotated with @HiltViewModel.
  • Create an activity or fragment class that displays the data on the screen and is annotated with @AndroidEntryPoint.

For example, we will create a simple app that stores and displays a list of users. Each user has an id, a name, and an email.

First, we need to add the Room and Hilt dependencies to our project’s build.gradle files:

// Project-level build.gradle
buildscript {
...
dependencies {
...
classpath 'com.google.dagger:hilt-android-gradle-plugin:2.40.5'
}
}

// Module-level build.gradle
plugins {
...
id 'kotlin-kapt'
id 'dagger.hilt.android.plugin'
}

dependencies {
...
// Room
implementation "androidx.room:room-runtime:2.3.0"
kapt "androidx.room:room-compiler:2.3.0"

// Hilt
implementation "com.google.dagger:hilt-android:2.40.5"
kapt "com.google.dagger:hilt-android-compiler:2.40.5"
}

Next, we need to define our data entity as a class annotated with @Entity:

@Entity(tableName = "users")
data class User(
@PrimaryKey val id: Int,
val name: String,
val email: String
)

Then, we need to create a DAO interface annotated with @Dao that defines the methods to access our data:

@Dao
interface UserDao {

@Query("SELECT * FROM users")
fun getAllUsers(): List<User>

@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertUser(user: User)

@Delete
fun deleteUser(user: User)
}

After that, we need to create a database class that extends RoomDatabase and is annotated with @Database and @HiltAndroidApp:

@Database(entities = [User::class], version = 1)
abstract class UserDatabase : RoomDatabase() {

abstract fun userDao(): UserDao

}

@HiltAndroidApp
class MyApp : Application()

Next, we need to create a repository class that provides an abstraction layer over our data sources and is annotated with @Inject:

class UserRepository @Inject constructor(
private val userDao: UserDao
) {

fun getAllUsers(): List<User> {
return userDao.getAllUsers()
}

fun insertUser(user: User) {
userDao.insertUser(user)
}

fun deleteUser(user: User) {
userDao.deleteUser(user)
}
}

Then, we need to create a view model class that exposes the data to the UI and is annotated with @HiltViewModel:

@HiltViewModel
class UserViewModel @Inject constructor(
private val userRepository: UserRepository
) : ViewModel() {

fun getAllUsers(): List<User> {
return userRepository.getAllUsers()
}

fun insertUser(user: User) {
userRepository.insertUser(user)
}

fun deleteUser(user: User) {
userRepository.deleteUser(user)
}
}

Finally, we need to create an activity or fragment class that displays the data on the screen and is annotated with @AndroidEntryPoint:

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

private val userViewModel: UserViewModel by viewModels()

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Display the list of users
val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
recyclerView.layoutManager = LinearLayoutManager(this)
val adapter = UserAdapter()
recyclerView.adapter = adapter
adapter.submitList(userViewModel.getAllUsers())

// Add a new user
val addButton = findViewById<Button>(R.id.add_button)
addButton.setOnClickListener {
val user = User(1, "Alice", "alice@example.com")
userViewModel.insertUser(user)
adapter.submitList(userViewModel.getAllUsers())
}

// Delete a user
val deleteButton = findViewById<Button>(R.id.delete_button)
deleteButton.setOnClickListener {
val user = User(1, "Alice", "alice@example.com")
userViewModel.deleteUser(user)
adapter.submitList(userViewModel.getAllUsers())
}
}
}

If you want to learn more about Room database with Hilt in Kotlin and how to use them to store and access data in your Android app, you can check out the following resources:

Room database with Hilt in Kotlin is a great way to store and access data in your Android app. With Room and Hilt skills, you can build better apps faster and easier. So what are you waiting for? Start storing today!

--

--

Reza Ramesh

I am an Android developer and UI/UX designer with 4 years of experience in creating engaging and user-friendly mobile applications