What is Room?
Room will automatically translate these annotations into SQLite instructions/queries to perform the correspondent operations into the DB engine.
Room architecture looks like follow:
The three major components of Room are:
- Database: It represents the DB, it is an object that holds a connection to the SQLite DB and all the operations are executed through it. It is annotated with @Database.
- Entity: Represents a table within the Room Database. It should be annotated with @Entity.
- DAO: An interface that contains the methods to access the Database. It is annotated with @Dao .
Here is an example Room Database in Kotlin
STEP – 1 Add Dependency in app level buid.gradle file
dependencies {
def room_version = "2.2.5"
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version" // For Kotlin use kapt
}
Also we need to add plugin in build.gradle file
apply plugin: 'kotlin-kapt'
Now we want to create a table in which we can store users so we have to do following steps
STEP- 2 Create a kotlin data class
@Entity
data class User(
@PrimaryKey val uid: Int,
@ColumnInfo(name = "first_name") val firstName: String?,
@ColumnInfo(name = "last_name") val lastName: String?
)
Already mentioned entity is a table in Room database so we want to create a table with table name User (table name will be same as data class name) and will have 3 fields- uid (which will be Primary key), first_name and last_name.
STEP – 3 Create an interface in kotlin
@Dao
interface UserDao {
@Query("SELECT * FROM user")
fun getAll(): List
@Query("SELECT * FROM user WHERE uid IN (:userIds)")
fun loadAllByIds(userIds: IntArray): List
@Query("SELECT * FROM user WHERE first_name LIKE :first AND " +
"last_name LIKE :last LIMIT 1")
fun findByName(first: String, last: String): User
@Insert
fun insertAll(vararg users: User)
@Delete
fun delete(user: User)
}
@Dao represent the database methods to be used, we use @Insert for inserting data, @delete for deleting data, and @Query to query data.
STEP – 4 Create a database
@Database(entities = arrayOf(User::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
STEP – 5 Call this database in your MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
thread{
val db = Room.databaseBuilder(
applicationContext,
AppDatabase::class.java, "database-name"
).build() // 1
db.userDao().insertAll(User(1, "Jayant", "Dhingra")) // 2
}
}
}
Understanding MainActivity
Part 1 => We are creating a Room database builder class then passing the application context , databse class and database name.
Part 2 => We are calling insertAll method from user Dao.
Thats all Folks!!