August 13, 2021

Android and Room

By lj007

Room

Room is ORM tool, which helps you to map your sqlite database tables to Objects. Room will actually used to remove pojo’s for database operations like insert, update, get operations.
So how to use Room:
Import room in your application:

dependencies {
   def paging_version = "1.0.0"
   implementation "android.arch.persistence.room:runtime:$room_version"
   kapt "android.arch.persistence.room:compiler:$room_version"
}

Room uses Annotations bases processing. If you want to create Database then you can use @Database, for table you can define class with @Entity annotation. To make transaction on table you need to create @Dao interface.

How your database file will looks like:

@Database(entities = (arrayOf(UserActionHistory::class)), version = 1)
@TypeConverters(Converter::class)
abstract class Database : RoomDatabase() {
    companion object {
        private var instance: WaveDatabase? = null        
        fun getDatabase(context: Context): Database {
            if (instance == null) {
                instance = Room.databaseBuilder(context.applicationContext, Database::class.java, "wave_room_db").fallbackToDestructiveMigration().build()
            }
            return instance!!
        }
    }

    abstract fun userActionHistoryDao(): UserActionHistoryDao
}

You can see database file here. It contains UserActionHistory which is table. UserActionHistoryDao is used for insert history or get history from table.
To save list of premitive data type variable, you can use @TypeConverters. You can also store list of objects with TypeConverters.

@Entity(indices = [(Index("id"))])
class UserActionHistory {
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0

    var serviceId: Int = 0
    var fieldId: Long = 0
    var status: Int = 0
}

Here is your Dao file

@Dao
interface UserActionHistoryDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(actionHistory: UserActionHistory)

    @Query("select * from UserActionHistory where status =:status")
    fun getAllActionHistory(status: Int): List

    @Query("update UserActionHistory set status =:status where id in (:ids)")
    fun changeActionHistoryStatus(ids: ArrayList, status: Int)

    @Query("update UserActionHistory set status =:status where id = :id")
    fun changeActionHistoryStatus(id: Long, status: Int)

    @Query("delete from UserActionHistory where id = :id")
    fun deleteActionHistory(id: Long)
}

To get informations from table you can just use below code:

Database.getDatabase(context).userActionHistoryDao().getAllActionHistory(1);