Room Database | Android Jetpack

In this article, We will discuss Room Database for Android App Development and how we can insert, delete, update and get data from our Room Database in Just 2 minutes. Before going onward, first, we should know what Room Database is? and why do we need a Room Database? The Room persistence library provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite. In particular, Room provides the following benefits:

  • Compile-time verification of SQL queries.
  • Convenience annotations that minimize repetitive and error-prone boilerplate code.
  • Streamlined database migration paths.

image.png

Let's create our Android App with Room Database. First of all, we need to add some dependencies in our Gradle file:

dependencies {
    def room_version = "2.3.0"

    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"
}

Now we need to create an @Entity class, we call it as User for our Room Database which works as a table:

@Entity
data class User(
    @PrimaryKey val uid: Int,
    val firstName: String?,
    val lastName: String?
)

Now we need to create our @Dao (Data Access Object) interface which is UserDao for insert, update, delete and get in our Room Database. We use @Query to fetch or get users from our database, @Insert to insert users in the database, @Update to update the particular user in our database, @Delete to delete a particular user in our database.

@Dao
interface UserDao {

    @Query("SELECT * FROM user")
    suspend fun getAll(): List<User>

    @Insert
    suspend fun insertAll(vararg users: User)

    @Delete
    suspend fun delete(user: User)

    @Update
    suspend fun update(user: User)
}

Now we need to create our abstract database class, we call it as AppDatabase and inherit that with RoomDatabase class.

@Database(entities = arrayOf(User::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao

    companion object {
        private var instance: AppDatabase? = null

        @Synchronized
        fun getInstance(ctx: Context): AppDatabase {
            if (instance == null) {
                instance =
                        Room.databaseBuilder(ctx.applicationContext, AppDatabase::class.java, "database").build()
            }
            return instance!!
        }
    }
}

Now we are all done with Room Database and we are ready to do operations like insert, delete, update and fetch from our ViewModel class as below:

viewModelScope.launch(Dispatchers.IO) {
    val userDao = database.userDao()
    val users: List<User> = userDao.getAll()
}

Show your love by sharing this article with your fellow developers.

(Follow me for more content about Android and other technologies. If you have any questions, go ahead and ask me here or email me at arsalankhan994@gmail.com and I'll do my best to respond)