Android Jetpack

Room Advanced - 2 (DB)

----___<<<<< 2023. 2. 2. 07:21

 

id 'kotlin-kapt'
		// ROOM
    implementation "androidx.room:room-runtime:2.5.0"
    kapt "androidx.room:room-compiler:2.5.0"

    // optional - Kotlin Extensions and Coroutines support for Room
    implementation "androidx.room:room-ktx:2.5.0"

    // viewModel coroutine
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1"

    // byViewModels
    implementation 'androidx.activity:activity-ktx:1.6.1'

    // liveData
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.5.1"

 

@Database(entities = [NumberEntity::class], version = 1)
abstract class MyDatabase : RoomDatabase() {
abstract fun numberDao() : NumberDao
companion object {
@Volatile
private var INSTANCE : MyDatabase? = null
fun getDatabase(
context: Context
) : MyDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
MyDatabase::class.java,
"number_database"
)
.fallbackToDestructiveMigration()
.build()
INSTANCE = instance
instance
}
}
}
}
view raw MyDatabase.kt hosted with ❤ by GitHub
@Entity(tableName = "number_table")
data class NumberEntity (
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
var id : Int = 0,
@ColumnInfo(name = "randomNumber")
var randomNumber : String
)
view raw NumberEntity.kt hosted with ❤ by GitHub
@Dao
interface NumberDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun create(numberEntity: NumberEntity)
@Query("SELECT * FROM number_table")
fun read() : Flow<List<NumberEntity>>
@Update
fun update(numberEntity: NumberEntity)
@Delete
fun delete(numberEntity: NumberEntity)
}
view raw NumberDao.kt hosted with ❤ by GitHub