Room Database In Android

Room Database is a part of the Android Architecture factors which provides an abstraction subcaste over SQLite which allows for further robust database access while still furnishing the full power of SQLite.

Why use Room Database?

  • Compile-time verification of SQL queries. each @Query and @Entity is checked at the collect time.
  • Using Reflections to reduce the boilerplate law.
  • fluently integrated with other Architecture factors like LiveData, and RxJava.

What’s the difference between the room and the SQLite database?

  • In the case of SQLite, There’s no collect- time verification of raw SQLite queries. But in Room, there’s SQL confirmation at collect time.
  • As your schema changes, you need to modernize the affected SQL queries manually. Room solves this problem.
  • You need to use lots of boilerplate law to convert between SQL queries and Java data objects. But, Room maps our database objects to Java Object without boilerplate law.
  • Room is erected to work with LiveData and RxJava for data observation, while SQLite does not.

Room architecture looks like the following:

There Are principally 3 Major Components In Room.

1.@Entity

Entity Representation of table and columns come veritably easy. you have to annotate “@Entity ” to a class and the name of the class becomes the table name and, data members come the name of the columns. The “@Entity ” class represents an reality in a table.

@Entity(tableName = "user")
data class Users(@PrimaryKey(autoGenerate = true)var userId: Int? = null,val userName: String, var location: String, val email: String)

2.@Dao — Data Access Object

An Interface where we put all our SQL queries. We don’t bear to write whole queries now; we need to make a system and annotate with specific reflections like.

@Insert — Used to insert a record into the Room database.

@Delete — Used to delete records from the Room database.

@Update — Used to update records in Room Database.

@Query — Used to enter the Query like (SELECT FROM*)”

@Dao
interface UserDao {
    @Insert
    fun insertUser(users: Users)

    @Query("Select * from user")
    fun gelAllUsers(): List<Users>

    @Update
    fun updateUser(users: Users)

    @Delete
    fun deleteUser(users: Users)
}

3.@Database

This is an abstract class that extends RoomDatabase, this is where you define the realities( tables) and the interpretation number of your database. It contains the database holder and serves as the main access point for the underpinning connection.

@Database(entities = [Users::class], version = 1, exportSchema = false)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabaseas() {

    abstract fun userDaoa() : UserDao
}

 

Done with an explanation. Let’s launch with the perpetration part.

am going to produce a sample app for stoner operation using the room database in kotlin. In the app, I’ve added functionalities to fit , cancel, modernize and list all the druggies.

Step 1 — Add dependences

  • First, We need to add dependences for the room database in our build.gradle train.

Step 2 – produce a Model Class

The room creates a table for each class annotated with @Entity.

  • Annotate the class with @Entity and use the tableName property to set the name of the table.
  • Set the primary key by adding the “@primaryKey ” reflection to the correct fields — in our case, this is the ID of the stoner.
  • Set the name of the columns for the class fields using the @ColumnInfo( name = “column_name ”) reflection. Feel free to skip this step if your fields formerly have the correct column name.
  • If multiple constructors are suitable, add the @Ignoreannotation to tell Room which should be used and which not.
@Entity(tableName = "user")
data class Users(@PrimaryKey(autoGenerate = true)var userId: Int? = null,val userName: String, var location: String, val email: String)

Step 3 — produce DAO( Data Access Objects)

DAOs are responsible for defining the styles that pierce the database.

@Dao
interface UserDao {

    @Insert
    fun insertUser(users: Users)

    @Query("Select * from user")
    fun gelAllUsers(): List<Users>

    @Update
    fun updateUser(users: Users)

    @Delete
    fun deleteUser(users: Users)

}

Then we just define introductory SQL database functionality like fitting and deleting entries. You can see that the @Query reflection is used to annotate functions that are using queries.

You can also use parameters in your queries using parametername.

Type Transformers

Type Transformers are used when we declare a property that Room and SQL don’t know how to contribute. Let’s see an illustration of how to contribute the List data type.

class Converters {

    @TypeConverter
    fun fromString(value: String): List<String> {
        val listType = object : TypeToken<List<String>>() {

        }.type
        return Gson().fromJson(value, listType)
    }

    @TypeConverter
    fun fromArrayList(list: List<String>): String {
        val gson = Gson()
        return gson.toJson(list)
    }
}

Step 4 — produce the database

Now, Everything is ready to produce a Database. We can produce a Room Database by extending the RoomDatabase.

AppDatabase.kt

@Database(entities = [Users::class], version = 1, exportSchema = false)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {

    abstract fun userDao() : UserDao

    companion object {
        private var INSTANCE: AppDatabase? = null

        fun getInstance(context: Context): AppDatabase? {
            if (INSTANCE == null) {
                synchronized(AppDatabase::class) {
                    INSTANCE = Room.databaseBuilder(context.applicationContext,
                        AppDatabase::class.java, "user.db").allowMainThreadQueries()
                        .build()
                }
            }
            return INSTANCE
        }

        fun destroyInstance() {
            INSTANCE = null
        }
    }
}

Notice here:

  • This is an abstract class that has to extend from RoomDatabase.
  • It has to be annotated with @Database, it receives a list of realities with all the classes that compose the database( all these classes have to be annotated with @Entity). We also have to give a database interpretation..
  • We’ve to declare an abstract function for each of the realities included in the @Database reflection, this function has to return the correspondentDAO( A class annotated with @Dao)..
  • Eventually, we declare a companion object to get stationary access to the system getAppDataBase which gives us a singleton case of the database.

Step 5 — CRUD operation on Room Database

Now the room database is ready for the CRUD operation.

UserRepository.kt

class UserRepository(context: Context) {

    var db: UserDao = AppDatabase.getInstance(context)?.userDao()!!


    //Fetch All the Users
    fun getAllUsers(): List<Users> {
        return db.gelAllUsers()
    }

    // Insert new user
    fun insertUser(users: Users) {
        insertAsyncTask(db).execute(users)
    }

    // update user
    fun updateUser(users: Users) {
        db.updateUser(users)
    }

    // Delete user
    fun deleteUser(users: Users) {
        db.deleteUser(users)
    }

    private class insertAsyncTask internal constructor(private val usersDao: UserDao) :
        AsyncTask<Users, Void, Void>() {

        override fun doInBackground(vararg params: Users): Void? {
            usersDao.insertUser(params[0])
            return null
        }
    }
}

 

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories