【ANDROID STUDIO】Room Data Persistence Library

 apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 30
buildToolsVersion "29.0.3"

defaultConfig {

applicationId "com.example.roomdemo"
minSdkVersion 24
targetSdkVersion 30
versionCode 1
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
dataBinding{
enabled = true
}

}

dependencies {
def lifecycle_version = "2.3.1"
def room_version = "2.3.0"

// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
// Annotation processor
kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"

implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"

// optional - Kotlin Extensions and Coroutines support for Room
implementation "androidx.room:room-ktx:$room_version"

//coroutines
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3'
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'androidx.core:core-ktx:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation 'androidx.recyclerview:recyclerview:1.2.0'
}
package com.example.roomdemo.db

import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity(tableName = "subscriber_data_table")
data class Subscriber (

@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "subscriber_name")
val id : Int,

@ColumnInfo(name = "subscriber_id")
val name : String,

@ColumnInfo(name = "subscriber_email")
val email : String
)


package com.example.roomdemo.db

import androidx.lifecycle.LiveData
import androidx.room.*

@Dao
interface SubscriberDAO {
@Insert
suspend fun insertSubscriber(subscriber: Subscriber): Long

@Update
suspend fun updateSubscriber(subscriber: Subscriber)

@Delete
suspend fun deleteSubscriber(subscriber: Subscriber)

@Query("DELETE FROM subscriber_data_table")
suspend fun deleteAll()

@Query("SELECT * FROM subscriber_data_table")
fun getAllSubscribers(): LiveData<List<Subscriber>>
}

package com.example.roomdemo.db

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

@Database(entities = [Subscriber::class],version = 1)
abstract class SubscriberDatabase : RoomDatabase() {

abstract val subscriberDAO: SubscriberDAO

companion object {
@Volatile
private var INSTANCE: SubscriberDatabase? = null
fun getInstance(context: Context): SubscriberDatabase {
synchronized(this) {
var instance = INSTANCE
if (instance == null) {
instance = Room.databaseBuilder(
context.applicationContext,
SubscriberDatabase::class.java,
"subscriber_data_database"
).build()
}
return instance
}
}

}
}


package com.example.roomdemo.db

class SubscriberRepository(private val dao : SubscriberDAO) {

val subscribers = dao.getAllSubscribers()

suspend fun insert(subscriber: Subscriber) {
dao.insertSubscriber(subscriber)
}

suspend fun update(subscriber: Subscriber) {
dao.updateSubscriber(subscriber)
}

suspend fun delete(subscriber: Subscriber) {
dao.deleteSubscriber(subscriber)
}

suspend fun deleteAll() {
dao.deleteAll()
}
}

package com.example.roomdemo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.roomdemo.databinding.ActivityMainBinding
import com.example.roomdemo.db.SubscriberDatabase
import com.example.roomdemo.db.SubscriberRepository

class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var subscriberViewModel: SubscriberViewModel

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this,R.layout.activity_main)
val dao = SubscriberDatabase.getInstance(application).subscriberDAO
val repository = SubscriberRepository(dao)
val factory = SubscriberViewModelFactory(repository)
subscriberViewModel = ViewModelProvider(this,factory).get(SubscriberViewModel::class.java)
binding.myViewModel = subscriberViewModel
binding.lifecycleOwner = this
displaySubscribersList()
}

private fun displaySubscribersList() {
subscriberViewModel.subscribers.observe(this, Observer {
Log.i("MYTAG",it.toString())
})

}
}
package com.example.roomdemo

import androidx.databinding.Bindable
import androidx.databinding.Observable
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.roomdemo.db.Subscriber
import com.example.roomdemo.db.SubscriberRepository
import kotlinx.coroutines.launch

class SubscriberViewModel(private val repository: SubscriberRepository) : ViewModel(),Observable {

val subscribers = repository.subscribers
@Bindable
val inputName = MutableLiveData<String>()
@Bindable
val inputEmail = MutableLiveData<String>()
@Bindable
val saveOrUpdateButtonText = MutableLiveData<String>()
@Bindable
val clearAllOrDeleteButtonText = MutableLiveData<String>()

init {
saveOrUpdateButtonText.value = "Save"
clearAllOrDeleteButtonText.value = "Clear All"
}

fun saveOrUpdate() {
val name = inputName.value!!
val email = inputEmail.value!!
insert(Subscriber(0, name, email))
inputName.value = null
inputEmail.value = null
}

fun clearAllOrDelete() {
clearAll()
}

fun insert(subscriber: Subscriber)= viewModelScope.launch {
repository.insert(subscriber)
}

fun update(subscriber: Subscriber) = viewModelScope.launch {
repository.update(subscriber)
}

fun delete(subscriber: Subscriber) = viewModelScope.launch {
repository.delete(subscriber)
}

fun clearAll()=viewModelScope.launch {
repository.deleteAll()
}

override fun removeOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {

}

override fun addOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {

}
}

package com.example.roomdemo

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.roomdemo.db.SubscriberRepository

class SubscriberViewModelFactory(private val repository: SubscriberRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(SubscriberViewModel::class.java)) {
return SubscriberViewModel(repository) as T
}
throw IllegalArgumentException("Unknown View Model class")
}
}


No comments:

Power Is Shifting Rapidly to Indie Creators

The exodus from Twitter since the election is a sign of things to come ͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ...

Contact Form

Name

Email *

Message *