Android Jetpack

Coroutine - 3 (Room + Coroutine)

----___<<<<< 2022. 2. 27. 19:43

개복치개발자 강의는 아래의 링크에서 확인할 수 있습니다.

 

개복치개발자 | Linktree

uyalae@naver.com

linktr.ee

 

 자 이번에는 이전에 했던 Room을 좀 더 발전시켜보겠습니다.

 

https://philosopher-chan.tistory.com/1483

 

Android Room - 5 (Room + ViewModel + ViewModelScope + LiveData)

 개복치개발자 강의는 아래의 링크에서 확인할 수 있습니다. 개복치개발자 | Linktree uyalae@naver.com linktr.ee  Room을 이전에 배운 ViewModel과 LiveData를 이용해서 함께 사용해보도록 하겠습니다.  여기.

philosopher-chan.tistory.com

 

 아래와 같이 매우 간단한 앱입니다.

 

 전체 데이터를 불러오고

 

 데이터를 db에 쌓습니다.

 

 

 

 자, 그러면 이 친구들을 어떻게 하는건지 하나씩 보겠습니다.

 

 일단 xml파일들은 아래와 같고

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/goToAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="goToAddActivity"
/>
<TextView
android:id="@+id/textArea"
android:textSize="20dp"
android:text="text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AddActivity"
android:orientation="vertical">
<Button
android:id="@+id/add"
android:text="add"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="@+id/addText"
android:hint="addText"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/remove"
android:text="removeAll"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>

 

 폴더 구조는 아래와 같이 만들었습니다.

 

 

 gradle에 아래와 같이 넣어주고

 

// ROOM
def roomVersion = "2.4.0"

implementation("androidx.room:room-runtime:$roomVersion")
kapt("androidx.room:room-compiler:$roomVersion")
implementation("androidx.room:room-ktx:$roomVersion")

//ViewModelScope
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0")
id 'kotlin-kapt'

 

 전체 gradle은 아래와 같습니다.

plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'kotlin-kapt'
}
android {
compileSdk 31
defaultConfig {
applicationId "com.bokchi.androidview"
minSdk 21
targetSdk 31
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
// ROOM
def roomVersion = "2.4.0"
implementation("androidx.room:room-runtime:$roomVersion")
kapt("androidx.room:room-compiler:$roomVersion")
implementation("androidx.room:room-ktx:$roomVersion")
//ViewModelScope
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0")
}
view raw build.gradle hosted with ❤ by GitHub

 

그리고 나머지 코드들

 

@Entity(tableName = "myData_table")
data class MyData (
@PrimaryKey
@ColumnInfo(name = "myData")
val myData: String
)
view raw MyData.kt hosted with ❤ by GitHub
@Dao
interface MyDataDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insert(myData : MyData)
@Query("SELECT * FROM myData_table")
suspend fun getAll() : List<MyData>
@Query("DELETE FROM myData_table")
suspend fun removeAll()
}
view raw MyDataDao.kt hosted with ❤ by GitHub
@Database(entities = [MyData::class], version = 1)
abstract class MyDataRoomDatabase : RoomDatabase() {
abstract fun myDataDao() : MyDataDao
companion object {
@Volatile
private var INSTANCE: MyDataRoomDatabase? = null
fun getDatabase(
context: Context
) : MyDataRoomDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
MyDataRoomDatabase::class.java,
"myData_database"
)
.fallbackToDestructiveMigration()
.build()
INSTANCE = instance
instance
}
}
}
}
class Repository(private val myDataDao: MyDataDao) {
suspend fun insert(myData: MyData){
myDataDao.insert(myData)
}
suspend fun getAllData(): List<MyData> {
return myDataDao.getAll()
}
suspend fun removeData() {
myDataDao.removeAll()
}
}
view raw Repository.kt hosted with ❤ by GitHub
class MyDataViewModel (application: Application): AndroidViewModel(application) {
private val repository: Repository
private var mutableText = MutableLiveData<List<MyData>>()
val liveText : LiveData<List<MyData>>
get() = mutableText
init {
Log.d("MyDataViewModel", "init")
repository = Repository(MyDataRoomDatabase.getDatabase(application).myDataDao())
}
fun insert(myData: MyData) = viewModelScope.launch(Dispatchers.IO) {
repository.insert(myData)
}
fun getAll() = viewModelScope.launch(Dispatchers.IO) {
val dataList = repository.getAllData()
mutableText.postValue(dataList)
}
fun removeAll() = viewModelScope.launch(Dispatchers.IO) {
repository.removeData()
}
}
class AddActivity : AppCompatActivity() {
lateinit var viewModel: MyDataViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add)
viewModel = ViewModelProvider(this).get(MyDataViewModel::class.java)
val addBtn = findViewById<Button>(R.id.add)
addBtn.setOnClickListener {
val addText = findViewById<EditText>(R.id.addText).text.toString()
val myData = MyData(addText)
viewModel.insert(myData)
}
val removeBtn = findViewById<Button>(R.id.remove)
removeBtn.setOnClickListener {
viewModel.removeAll()
}
}
}
view raw AddActivity.kt hosted with ❤ by GitHub
class MainActivity : AppCompatActivity() {
lateinit var viewModel: MyDataViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewModel = ViewModelProvider(this)[MyDataViewModel::class.java]
val addBtn = findViewById<Button>(R.id.goToAdd)
addBtn.setOnClickListener {
val intent = Intent(this, AddActivity::class.java)
startActivity(intent)
}
val textArea = findViewById<TextView>(R.id.textArea)
viewModel.liveText.observe(this, Observer {
textArea.text = it.toString()
})
}
override fun onResume() {
super.onResume()
viewModel.getAll()
}
}
view raw MainActivity.kt hosted with ❤ by GitHub

'Android Jetpack' 카테고리의 다른 글

WorkManager - 1 (WorkManager란)  (0) 2022.03.06
Coroutine - 4 (Retrofit + Coroutine)  (0) 2022.03.02
Coroutine - 2 (Dispatchers)  (0) 2022.02.22
Coroutine - 1 (Coroutine이란?)  (0) 2022.02.20
Jetpack Navigation - 6 (Animation)  (0) 2022.02.19