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"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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 | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Entity(tableName = "number_table") | |
data class NumberEntity ( | |
@PrimaryKey(autoGenerate = true) | |
@ColumnInfo(name = "id") | |
var id : Int = 0, | |
@ColumnInfo(name = "randomNumber") | |
var randomNumber : String | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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) | |
} |