【ANDROID STUDIO】CRUD Room Data Persistence Library

 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
private var isUpdateOrDelete = false
private lateinit var subscriberToUpdateOrDelete : Subscriber
@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() {
if(isUpdateOrDelete) {
subscriberToUpdateOrDelete.name = inputName.value!!
subscriberToUpdateOrDelete.email = inputEmail.value!!
update(subscriberToUpdateOrDelete)
}else {

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

fun clearAllOrDelete() {
if(isUpdateOrDelete) {
delete(subscriberToUpdateOrDelete)
}else {
clearAll()
}
}

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

fun update(subscriber: Subscriber) = viewModelScope.launch {
repository.update(subscriber)
inputName.value = null
inputEmail.value = null
isUpdateOrDelete = false
saveOrUpdateButtonText.value = "Save"
clearAllOrDeleteButtonText.value = "Clear All"
}

fun delete(subscriber: Subscriber) = viewModelScope.launch {
repository.delete(subscriber)
inputName.value = null
inputEmail.value = null
isUpdateOrDelete = false
saveOrUpdateButtonText.value = "Save"
clearAllOrDeleteButtonText.value = "Clear All"

}

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

fun initUpdateAndDelete(subscriber: Subscriber) {
inputName.value = subscriber.name
inputEmail.value = subscriber.email
isUpdateOrDelete = true
subscriberToUpdateOrDelete = subscriber
saveOrUpdateButtonText.value = "Update"
clearAllOrDeleteButtonText.value = "Delete"

}


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

}

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

}
}
package com.example.roomdemo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.roomdemo.databinding.ActivityMainBinding
import com.example.roomdemo.db.Subscriber
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
initRecyclerView()

}

private fun initRecyclerView() {

binding.subscriberRecyclerView.layoutManager = LinearLayoutManager(this)
displaySubscribersList()

}

private fun displaySubscribersList() {
subscriberViewModel.subscribers.observe(this, Observer {
binding.subscriberRecyclerView.adapter = MyRecyclerViewAdapter(it, {selecteditem:Subscriber->listItemClicked(selecteditem)})
})

}

private fun listItemClicked(subscriber: Subscriber) {
subscriberViewModel.initUpdateAndDelete(subscriber)
}

}

package com.example.roomdemo

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.roomdemo.databinding.ListItemBinding
import com.example.roomdemo.db.Subscriber

class MyRecyclerViewAdapter(
private val subscribersList: List<Subscriber>,
private val clickListener: (Subscriber) -> Unit
) : RecyclerView.Adapter<MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding: ListItemBinding =
DataBindingUtil.inflate(layoutInflater, R.layout.list_item, parent, false)
return MyViewHolder(binding)
}

override fun getItemCount(): Int {
return subscribersList.size
}

override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bind(subscribersList[position], clickListener)
}

}

class MyViewHolder(val binding: ListItemBinding) : RecyclerView.ViewHolder(binding.root) {

fun bind(subscriber: Subscriber, clickListener: (Subscriber) -> Unit) {
binding.nameTextView.text = subscriber.name
binding.emailTextView.text = subscriber.email
binding.listItemLayout.setOnClickListener{
clickListener(subscriber)
}
}
}
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")
}
}

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")
var id : Int,

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

@ColumnInfo(name = "subscriber_email")
var 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()
}
}


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 *