简体   繁体   English

Android:Kotlin 房间如何从表中获取唯一数据并在回收视图中使用它

[英]Android: Kotlin Room how to take unique data from table and use this in recycle view

I have a table with lessons and I need to select all the unique group names from there to display them in the recycle view我有一张包含课程的表格,我需要从那里输入 select 所有唯一的组名,以便在回收视图中显示它们

Lesson data class课时资料 class

@Entity(tableName = "lesson_table")
data class Lesson (
    @PrimaryKey(autoGenerate = true) val id: Int?,
    @ColumnInfo(name = "lesson_name") val lessonName: String?,
    @ColumnInfo(name = "Group_name") val groupName: String?,
    @ColumnInfo(name = "day") val day: Int?
)

LessonDAO课程DAO

@Dao
interface  LessonDao {
    @Query("SELECT * FROM lesson_table")
    fun getAll(): List<Lesson>
    @Query("SELECT DISTINCT Group_name FROM lesson_table")
    fun findallgroup(): List<Lesson>

And this in fragment code to inset data in rcview这在片段代码中用于在 rcview 中插入数据

  private fun init(){
        binding.apply {

            gridLayoutManager = GridLayoutManager(requireContext(), 2, LinearLayoutManager.VERTICAL, false)
            rcView.layoutManager = gridLayoutManager
            rcView.adapter=adapter

        }
        GlobalScope.launch { adapter.addItems(appDb.lessonDao().findallgroup())}
    }

It doesnt work, but if I use getAll() from DAO its works Please help它不起作用,但如果我使用 DAO 中的 getAll() 它的作品请帮忙

PS if I use findallgroup() i get that error PS 如果我使用 findallgroup() 我得到那个错误

E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-1
    Process: com.example.calendar2, PID: 5833
    android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

Don't use GlobalScope .不要使用GlobalScope You should use a lifecycle scope so it is bound to the Main thread, which is required when working with any UI components.您应该使用生命周期 scope,以便将其绑定到主线程,这在使用任何 UI 组件时都是必需的。 A lifecycle scope also automatically cancels its coroutines when the view is destroyed, which avoids leaking memory or causing crashes that could happen when trying to reference views that no longer exist.当视图被销毁时,生命周期 scope 也会自动取消其协程,这避免了泄漏 memory 或导致在尝试引用不再存在的视图时可能发生的崩溃。

In an Activity:在活动中:

lifecycleScope.launch { adapter.addItems(appDb.lessonDao().findallgroup()) }

In a Fragment:在片段中:

viewLifecycle.lifecycleScope.launch { adapter.addItems(appDb.lessonDao().findallgroup()) }

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM