개발모음집

android jetpack room 본문

Android

android jetpack room

void 2019. 7. 11. 10:00

package com.voiddevloper.festivalkorea.Room

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.OnConflictStrategy.REPLACE
import androidx.room.Query
import com.voiddevloper.festivalkorea.models.FestivalData

// SQL문을 객체화해놓은 코드
@Dao
interface FestivalsDao {

@Query("SELECT * FROM FESTIVAL_INFO_TB")
fun getRowAll(): MutableList<FestivalData>

/* import android.arch.persistence.room.OnConflictStrategy.REPLACE */
// festivals 객체 하나를 insert하는 것
@Insert(onConflict = REPLACE)
fun insertFestival(festivals: Festivals)

@Query("DELETE from FESTIVAL_INFO_TB")
fun deleteRowAll()

}

 

 

package com.voiddevloper.festivalkorea.Room

import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.voiddevloper.festivalkorea.singleton.Utils.dateTime

// Room 을 이용하여 DB 저장하기
// 테이블 형식 지정
@Entity(tableName = "FESTIVAL_INFO_TB")
class Festivals(@PrimaryKey(autoGenerate = true) var id: Int?,
@ColumnInfo(name = "bgUri") var bgUri: Int?,
@ColumnInfo(name = "nameEn") var nameEn: String?,
@ColumnInfo(name = "nameKr") var nameKr: String?,
@ColumnInfo(name = "introduce") var introduce: String?,
@ColumnInfo(name = "officialUrl") var officialUrl: String?,
@ColumnInfo(name = "snsUrl") var snsUrl: String?,
@ColumnInfo(name = "calendar") var calendar: String?,
@ColumnInfo(name = "reservation") var reservation: String?,
@ColumnInfo(name = "reservationDate") var reservationDate: String?,
@ColumnInfo(name = "createdAt") val createdAt: String?,
@ColumnInfo(name = "updatedAt") val updatedAt: String?
){
constructor(): this(null, null, null, null, null, null, null, null, null, null, dateTime(),dateTime())
}

 

package com.voiddevloper.festivalkorea.Room

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase

// Entity 모델(Festivals)을 기반으로 하고, DAO의 메소드를 가지고 있는 데이터베이스를 생성하자.
// 여러 테이블이면, @Database(entities = [Festivals::class, Logs::class], version = 3, exportSchema = false) 이런 식으로 클래스 파일을 추가해주면 됨, 그리고 데이터베이스 변경이 있을 때마다 버전을 올려줘야한다. 안 바꿔주면 에러 발생
@Database(entities = [Festivals::class], version = 1, exportSchema = false)
abstract class FestivalsDB: RoomDatabase() {

abstract fun festivalsDao(): FestivalsDao

companion object {
private var INSTANCE: FestivalsDB? = null

fun getInstance(context: Context): FestivalsDB? {
if (INSTANCE == null) {
synchronized(FestivalsDB::class) {
INSTANCE = Room.databaseBuilder(
context.applicationContext,
FestivalsDB::class.java, "FESTIVAL.db"
)
.fallbackToDestructiveMigration()
.build()
}
}
return INSTANCE
}

fun destroyInstance() {
INSTANCE = null
}


}
}

// FESTIVAL.db파일, FESTIVAL_INFO_TB 테이블에 Festivals객체 insert하기
val addRowRunnable = Runnable {
val festival = Festivals()
festival.id = 2
festival.bgUri = 1
festival.nameEn = "Ultra"
festival.nameKr = "울트라"
festival.introduce = "확인"
festival.officialUrl = "www.naver.com"
festival.snsUrl = "www.naver.com"
festival.reservation = "www.naver.com"
festival.reservationDate = "www.naver.com"
festival.calendar = "1"
festivalsDb?.festivalsDao()?.insertFestival(festival)
}

val addRowThread = Thread(addRowRunnable)
addRowThread.start()

 

// db에 저장된 데이터를 불러오는 코드
val selectRunnable = Runnable {
try{
festivalInfoLists = festivalsDb?.festivalsDao()?.getRowAll()!!
logVerbose(TAG, "festivalInfoLists.toString(): "+festivalInfoLists.get(0).id)

} catch (e: Exception) {
logVerbose(TAG, "Error - $e")
}
}

val selectThread = Thread(selectRunnable)
selectThread.start()