— Android, Kotlin, Room — 1 min read
If you are building an Android application that requires a local database, Room is the recommended persistence library by Google. It provides an abstraction layer over SQLite, making it easier to work with the database and handle common tasks such as migrations.
To use Room in your Android project, add the following dependencies to your build.gradle file:
1dependencies {2 def room_version = "2.4.0"3
4 implementation "androidx.room:room-runtime:$room_version"5 kapt "androidx.room:room-compiler:$room_version"6}The room-runtime dependency includes the required classes and methods for working with Room, while the room-compiler dependency generates necessary code during compilation time.
Some additional dependencies include room-ktx which provides Kotlin extensions for Room, and room-testing which provides utilities for testing with Room.
Entities in Room represent tables in your database. To define an entity, create a data class annotated with the @Entity annotation, and specify the table name in the tableName parameter:
1@Entity(tableName = "users")2data class User(3 @PrimaryKey val id: Int,4 val name: String,5 val email: String6)The @PrimaryKey annotation is used to specify the primary key of the table.
To create a Room database, define an abstract class that extends RoomDatabase. Annotate the class with @Database and specify the entities and version number:
1@Database(entities = [User::class], version = 1)2abstract class AppDatabase : RoomDatabase() {3
4 abstract fun userDao(): UserDao5}The userDao() method returns an instance of UserDao, which is responsible for defining the queries to interact with the User table.
Data Access Objects (DAOs) are interfaces that define the methods to access and manipulate the database. To define a DAO, create an interface annotated with @Dao and define the query methods:
1@Dao2interface UserDao {3
4 @Query("SELECT * FROM users")5 fun getAllUsers(): List<User>6
7 @Insert(onConflict = OnConflictStrategy.REPLACE)8 suspend fun insert(user: User)9
10 @Delete11 suspend fun delete(user: User)12}In this example, getAllUsers() returns a list of all users in the table, insert(user: User) inserts a new user, and delete(user: User) deletes a user from the table.
To access the database, create an instance of AppDatabase using the Room.databaseBuilder() method:
1val db = Room.databaseBuilder(2 applicationContext,3 AppDatabase::class.java, "my-db"4).build()This creates a database with the name "my-db". You can then use the dao() method to obtain an instance of UserDao and execute the defined queries:
1lifecycleScope.launch {2 db.userDao().insert(User(1, "John Doe", "john@example.com"))3 4 val users = db.userDao().getAllUsers()5 Log.d("MainActivity", users.toString())6}In this example, a new user is inserted into the database, and then all users in the table are logged to the console.
Using Room with Android makes it easy to work with SQLite databases in your application. By defining entities, creating a database, and defining DAOs, you can easily perform common operations such as inserting, updating, and deleting data. With its powerful abstractions and annotations, Room can help simplify your database code and save development time.