๐ฅ Kotlin ์ผ๋ก Android Room DB ์ฌ์ฉํ๊ธฐ
๐ ์์
- build.gradle
- Entity, Dao, Database
โ build.gradle
plugins {
...
id 'kotlin-kapt'
}
dependencies {
...
implementation "androidx.room:room-runtime:2.3.0"
kapt "androidx.room:room-compiler:2.3.0"
}
โ Entity, Dao, Database
@Entity
data class Alarm (
@PrimaryKey(autoGenerate = true) val id: Int?,
@ColumnInfo(name = "alarmHour") val alarmHour: String,
@ColumnInfo(name = "alarmMinute") val alarmMinute: String
)
@Dao
interface AlarmDao {
@Query("SELECT * FROM alarm")
fun getAll() : List<Alarm>
@Insert
fun insert(alarm: Alarm)
@Delete
fun deleteAlarm(alarm: Alarm)
@Update
fun updateAlarm(alarm: Alarm)
}
@Database(entities = [Alarm::class], version = 1)
abstract class AlarmDataBase : RoomDatabase() {
abstract fun alarmDao(): AlarmDao
}
val db : AlarmDataBase = Room.databaseBuilder(
context,
AlarmDataBase::class.java,
AlarmFragment.ALARM_DB
).build()
val thread = Thread {
db.alarmDao().deleteAlarm(list!![id])
}
thread.start()
โ ๊ทธ ์ธ
- db์ ์ ๊ทผํ๊ณ ์ ํ ๋, database class ์์์ ์ ๊ทผํ๋๋ก ํจ์๋ฅผ ๋ฐ๋ก ๊ตฌํํ ์๋ ์๋ค.
- Thread ๋ suspend fun, coroutine ๋ฑ์ ์ฌ๋ฌ๊ฐ์ง ์ฌ์ฉ ๋ฐฉ๋ฒ์ด ์กด์ฌํ๋ค.