Room DB란?
Room DB 사용 이유
Room의 구조
코드 예제
1. Gradle 설정
id 'kotlin-kapt'
//RoomDB
implementation "androidx.room:room-ktx:2.3.0"
implementation "androidx.room:room-runtime:2.3.0"
kapt "androidx.room:room-compiler:2.3.0"
2. Entity 설정
@Entity
data class LoginEntity(
val username: String,
val password: String
) {
@PrimaryKey(autoGenerate = true) var id: Int = 0
}
3. Dao 설정
@Dao
interface LoginDao {
@Query("Select * From LoginEntity")
fun getLogin() : LoginEntity
@Query("DELETE From LoginEntity")
fun deleteLogin()
@Insert
fun insetLogin(loginEntity: LoginEntity)
}
4. Database 설정
@Database(
entities = [LoginEntity::class],
version = 1,
exportSchema = false
)
abstract class LoginDatabase: RoomDatabase() {
abstract fun loginDao() : LoginDao
companion object {
private var instance: LoginDatabase? = null
@Synchronized
fun getInstance(context: Context): LoginDatabase? {
if (instance == null) {
synchronized(LoginDatabase::class) {
instance = Room.databaseBuilder(
context.applicationContext,
LoginDatabase::class.java,
"login-database"
)
.build()
}
}
return instance
}
}
}
5. 사용
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var db: LoginDatabase
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
db = LoginDatabase.getInstance(applicationContext)!!
refreshLogin()
binding.btn.setOnClickListener {
addLogin()
refreshLogin()
startLogin()
}
}
private fun addLogin() {
val username = binding.etID.text.toString()
val password = binding.etPW.text.toString()
CoroutineScope(Dispatchers.IO).launch {
db.loginDao().insetLogin(LoginEntity(username, password))
}
}
private fun refreshLogin() {
CoroutineScope(Dispatchers.Main).launch {
val data = CoroutineScope(Dispatchers.IO).async {
db.loginDao().getLogin()
}.await()
if(data != null) {
binding.etID.setText("${data.username}")
binding.etPW.setText("${data.password}")
}
}
}
}
TypeConverter :
https://velog.io/@chc0331/TypeConverter