简体   繁体   中英

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

Lesson data 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
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

  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

PS if I use findallgroup() i get that error

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 . You should use a lifecycle scope so it is bound to the Main thread, which is required when working with any UI components. 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.

In an Activity:

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

In a Fragment:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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