繁体   English   中英

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

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

我有一张包含课程的表格,我需要从那里输入 select 所有唯一的组名,以便在回收视图中显示它们

课时资料 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?
)

课程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>

这在片段代码中用于在 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())}
    }

它不起作用,但如果我使用 DAO 中的 getAll() 它的作品请帮忙

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.

不要使用GlobalScope 您应该使用生命周期 scope,以便将其绑定到主线程,这在使用任何 UI 组件时都是必需的。 当视图被销毁时,生命周期 scope 也会自动取消其协程,这避免了泄漏 memory 或导致在尝试引用不再存在的视图时可能发生的崩溃。

在活动中:

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

在片段中:

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

暂无
暂无

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

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