Android Room DB

passยท2023๋…„ 2์›” 21์ผ
0

Android

๋ชฉ๋ก ๋ณด๊ธฐ
6/41

๐Ÿ”ฅ Kotlin ์œผ๋กœ Android Room DB ์‚ฌ์šฉํ•˜๊ธฐ


๐Ÿ“‘ ์ˆœ์„œ

  1. build.gradle
  2. 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 ๋“ฑ์˜ ์—ฌ๋Ÿฌ๊ฐ€์ง€ ์‚ฌ์šฉ ๋ฐฉ๋ฒ•์ด ์กด์žฌํ•œ๋‹ค.
profile
์•ˆ๋“œ๋กœ์ด๋“œ ๊ฐœ๋ฐœ์ž ์ง€๋ง์ƒ

0๊ฐœ์˜ ๋Œ“๊ธ€