| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| 19 | 20 | 21 | 22 | 23 | 24 | 25 |
| 26 | 27 | 28 | 29 | 30 |
- androidstudio
- 티스토리챌린지
- algoritm
- AlertDailog
- 안드로이드#코틀린
- algorithm #
- android #androidstudio #fragmentdialog #kotlin
- 오블완
- 안드로이드 앱 아키텍처
- mutablestateof
- Dynamic Programing
- compose
- 카카오로그인
- KioskMode
- mutablestatelistof
- android #google console
- android12
- alogrithm
- kotlin
- algorithm
- Android
- cs #computer #network #internet
- DFS
- android #androidstudio #zsh
- BFS
- Jetpack Compose
- android #android studio #compose #kotlin
- android #androidstudio #compose #kotlin
- 백준 5052
- Bluetooth Permission
- Today
- Total
스태틱하게 개발중
[Android] Room을 사용하는 방법 본문
Room은 로컬에 데이터를 캐싱할수 있도록 안드로이드가 제공하는 Library이다.
네트워크 연결이 끊긴 오프라인 환경에서도 콘텐츠를 볼 수가 있다.
만약 네트워크가 다시 연결된다면 콘텐츠의 변경사항이 동기화가 된다.
Developer 공식문서에는 Room을 적극적으로 사용하도록 권장하고있다.
https://developer.android.com/training/data-storage/room?hl=ko
Room을 사용하여 로컬 데이터베이스에 데이터 저장 | Android 개발자 | Android Developers
Room 라이브러리를 사용하여 더 쉽게 데이터를 유지하는 방법 알아보기
developer.android.com
먼저 Room을 사용하기 위해서 의존성부터 추가해준다.
implementation "androidx.room:room-runtime:2.4.1"
kapt "androidx.room:room-compiler:2.4.1"
Room을 사용하기 위해서는 아래와 같이 3가지 구성요소가 필요하다.
1. Entity
데이터베이스의 테이블을 정의하기 위한 속성이다.
@Entity 어노를테이션을 지정해주고, 원하는 테이블 이름을 (tableName = "student") 이렇게 변경할수도 있다.
만약 studentId를 기본키로 지정하고 싶다면 @PrimaryKey 어노테이션을 지정한다.
@ColumnInfo를 지정하여 속성이름을 다르게 사용할 수 있다.
@Entity(tableName = "student")
data class StudentEntity(
@PrimaryKey(autoGenerate = true) var id: Int = 0,
@ColumnInfo(student_number) var number : String,
var name : String,
var department: String
)
2. DAO
Database에 있는 데이터에 접근하기 위한 메소드들을 포함한다.
@Dao 어노테이션을 지정해주고 메소드들을 구현해준다.
Room은 어노테이션을 통해 다양한 쿼리를 편리하게 작성하게 해준다.
@Dao
interface StudentDao {
@Insert
fun insert(student: Student)
@Update
fun update()
@Delete
fun delete()
}
@Query 어노테이션을 지정하면 직접 쿼리문을 작성할 수 있다.
예를들어 ("SELECT * from student WHRER name = :name")은 특정 이름을 가진 학생을 검색할 수 있다.
@Dao
interface DAO {
@Query("SELECT * from student WHRER name = :name")
fun getStudentByName(name)
@Query("SELECT * from student")
fun getAll(): List<Student>
@Query("DELETE from student")
fun clearAll()
}
3. Database
마지막으로 데이터베이스에 접근할 수 있도록 RoomDatabase를 상속받는 추상 클래스를 만든다.
클래스가 Room 데이터베이스가 되도록 @Database 어노테이션을 붙혀주고, 엔티티를 넣어준다. 만약 여러개의 엔티티를 넣고 싶다면 arrayOf(Student::class, Student2::class) 로 넣어주면 된다.
version 값은 테이터베이스를 업데이트 할때 구조가 변경된다면 version = 1, version = 2 이런식으로 구분해주는 역활을 한다.
Database 객체를 인스턴스화 하는 작업은 비용이 많이 들어가기 때문에 싱글톤패턴으로 만드는 것을 권장한다.
@Database(entities = [StudentEntity::class], version = 1)
abstract class StudentDatabase : RoomDatabase() {
abstract fun studentDao(): StudentDao
companion object {
@Volatile
private var INSTANCE: StudentDatabase? = null
fun getDatabase(context: Context): StudentDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
StudentDatabase::class.java,
"student_database"
).build()
INSTANCE = instance
instance
}
}
}
}
여기까지가 Room 을 사용하기 위한 준비단계이다.
안드로이드에서는 데이터베이스 작업을 Coroutine이나 RxJava를 사용하여 비동기로 처리해주어야 한다.
비동기로 데이터베이스 작업을 하는방법은 다음포스팅에서 해보려고 한다.
'Android' 카테고리의 다른 글
| [Android] FragmentDialog 동적으로 Size, 위치 조절하기 (0) | 2023.09.07 |
|---|---|
| [Android] WebView 파일 다운로드 기능 (0) | 2023.08.23 |
| [Android] 안드로이드 프로젝트 카카오 로그인 적용해보기 (0) | 2022.06.29 |
| [Android] 카카오 로그인 SDK사용을 위해 설정하기 (0) | 2022.06.29 |
| [Android] RxJava를 사용하여 Room 데이터 사용하기 (0) | 2022.02.11 |