简体   繁体   English

我想使用 Room Database、LiveData 和 Viewmodel 实时更新我的适配器。 但不知道如何

[英]I want to update my adapter in realtime using Room Database , LiveData and Viewmodel. But don't know how

I have an recyclerview adapter whose attribute called timeLeft which means it can count down the time from set time with time now in every single recyclerview item.我有一个 recyclerview 适配器,它的属性称为 timeLeft,这意味着它可以在每个 recyclerview 项目中从设定时间开始倒计时。 I want it updated in real time but don't know how.我希望它实时更新,但不知道如何。 Please help me [Example picture][1] [1]: https://i.stack.imgur.com/8le2s.png Data file请帮帮我[示例图片][1] [1]:https://i.stack.imgur.com/8le2s.png 数据文件

@Parcelize
@Entity(tableName = "task_table")
data class Task(
    //id is the PrimaryKey which is auto generated by Android Room Database
    @PrimaryKey(autoGenerate = true)
    val id: Int,
    val date: String,
    val content: String,
    var timeLeft: String,
    var isDone : Boolean
):Parcelable

Dao File道文件

@Dao
interface TaskDao {
    // means it will be just ignore if there is a new exactly same task then we're gonna just ignore it
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun addTask(task :Task)

    @Delete
    suspend fun deleteTask(task : Task)

    @Update
    suspend fun  updateTask(task : Task)

    @Query("SELECT * FROM task_table order by timeLeft ASC")
    fun readAllData(): LiveData<MutableList<Task>>
}

Repository File存储库文件

class TaskRepository (private val taskDao : TaskDao){
    val readAllData : LiveData<MutableList<Task>> = taskDao.readAllData()

    suspend fun addTask(task : Task){
        taskDao.addTask(task)
    }

    suspend fun deleteTask(task : Task)
    {
        taskDao.deleteTask(task)
    }

    suspend fun updateTask(task:Task)
    {
        taskDao.updateTask(task)
    }
}

View Model File查看 Model 文件

class TaskViewModel(application: Application) : AndroidViewModel(application) {
    val readAllData: LiveData<MutableList<Task>>
    private val repository: TaskRepository

    init {
        val taskDao = TaskDatabase.getDatabase(application).taskDao()
        repository = TaskRepository(taskDao)
        readAllData = repository.readAllData
    }

    fun addTask(task: Task) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.addTask(task)
        }
    }

    fun updateTask(task: Task) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.updateTask(task)
        }
    }

    fun deleteTask(task: Task) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.deleteTask(task)
        }
    }

}

Recycler View Adapter File Recycler 查看适配器文件

package com.example.superbtodo.fragments.list


import android.annotation.SuppressLint
import android.graphics.Paint
import android.text.style.StrikethroughSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.findNavController
import androidx.recyclerview.widget.RecyclerView
import com.example.superbtodo.R
import com.example.superbtodo.data.Task
import com.example.superbtodo.viewmodel.TaskViewModel

class ListAdapter() : RecyclerView.Adapter<ListAdapter.ViewHolder>() {
    private var tasks = mutableListOf<Task>()

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val contentTextView = itemView.findViewById(R.id.contentTxt) as TextView
        val timeTextView = itemView.findViewById(R.id.timeTxt) as TextView
        val timeLeftTextView = itemView.findViewById(R.id.timeLeftTxt) as TextView
        var isDoneCheckBox = itemView.findViewById(R.id.checkBtn) as RadioButton
        val taskLayout = itemView.findViewById(R.id.taskLayout) as RelativeLayout
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemView =
            LayoutInflater.from(parent.context).inflate(R.layout.task_layout, parent, false)
        return ViewHolder(itemView)
    }

    @SuppressLint("ResourceAsColor")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val currentItem = tasks[position]
        holder.contentTextView.text = currentItem.content
        holder.timeTextView.text = currentItem.date
        holder.timeLeftTextView.text = currentItem.timeLeft
        holder.isDoneCheckBox.isChecked = currentItem.isDone
        holder.taskLayout.setOnClickListener {
            val action =
                ListFragmentDirections.actionListFragmentToUpdateTaskDialogFragment(currentItem)
            holder.itemView.findNavController().navigate(action)
        }
        if (holder.isDoneCheckBox.isChecked) {
            holder.timeLeftTextView.visibility = View.GONE
            holder.contentTextView.apply {
                paintFlags = paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
                setTextColor(R.color.gone)
            }
            holder.timeTextView.apply {
                paintFlags = paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
                setTextColor(R.color.gone)
            }
        } else {
   holder.timeLeftTextView.visibility = View.VISIBLE
            holder.contentTextView.apply {
                paintFlags = 0
                setTextColor(R.color.black)
            }
            holder.timeTextView.apply {
                paintFlags = 0
                setTextColor(R.color.black)
            }
        }

    }

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


    @SuppressLint("NotifyDataSetChanged")
    fun setData(task: MutableList<Task>) {
        this.tasks = task as MutableList<Task>
        notifyDataSetChanged()
    }

    enter code here
    fun getTaskAt(position: Int): Task {
        return tasks[position]
    }
}

Repository File存储库文件

get live data from database in Repository and return to view model从存储库中的数据库获取实时数据并返回查看 model

    fun getLiveDataOfTask():MutableLiveData<MutableList<Task>> {
        return TaskDatabase.getDatabase(application).taskDao().readAllData()
    }

Add In View model class加入视图 model class

    fun getAllDataTask() = repository.readAllData

In Activity活动中

 viewModel?.getAllDataTask()?.observe(this) {
        //new Data come hear every time when data was change 
        changeAdapterData()
    }

In Adapter在适配器中

fun updateList(list: MutableList<Task>) {
    this.list = list
    notifyDataSetChanged()
}

And if you went to update only time in adapter item from save time and current time difference then add below code in adapter and ignore above code如果您从保存时间和当前时差仅更新适配器项中的时间,则在适配器中添加以下代码并忽略上述代码

//global variable
 private var handler: android.os.Handler? = null
 var hourly = SimpleDateFormat("ss") // add your time formate

    // in onBindViewHolder
    handler = Handler(Looper.getMainLooper())
    var periodicUpdate: Runnable? = null
    periodicUpdate = Runnable {
        try {
            holder.holderItemView.textView.text = hourly.format(System.currentTimeMillis())
            periodicUpdate?.let { handler?.postDelayed(it, 1000) }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    handler?.post(periodicUpdate)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 LiveData 更新 Room 数据库行<t>目的?</t> - How to update Room database row using a LiveData<T> object? 我想从ViewModel与我的View(Activity)进行交互。 从ViewModel使用View.VISIBLE - I want to interact with my View(Activity) from ViewModel. Using View.VISIBLE from ViewModel 如何在 Android 中使用 LiveData 和 ViewModel 不断更新 Firebase 实时数据库的查询 - How to constantly update query for Firebase Realtime Database with LiveData and ViewModel in Android Room LiveData,ViewModel。 按名称搜索。 奇怪的过滤行为 - Room LiveData, ViewModel. Search by name. Strange filtering behavior 如何使用存储库和ViewModel更新会议室数据库中的字段 - How do I update a field in a room database using a repository & viewmodel 如何使用 LiveData 从 Room 数据库更新文本视图? - How to update a text view from a Room database using LiveData? 如何使用房间持久性库和livedata更新数据库 - how to update database using room persistance library and livedata 如何使用 Room 获取 Livedata object 以更新片段? - How do I get a Livedata object to update on a fragment using Room? 带有LiveData,存储库和ViewModel的Room Database如何一起工作? - How does the Room Database with LiveData, repository, and viewmodel work together? 如何从 Room Dao 更改我的 LiveData 的 ViewModel 源 - How can I change in ViewModel source of my LiveData from Room Dao
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM