【问题标题】:Room Database entries in RecyclerViewRecyclerView 中的房间数据库条目
【发布时间】:2020-03-20 11:16:26
【问题描述】:

我想在 RecyclerView 中显示 Room Database 条目。到目前为止,我已经有了 Room 骨架,并且可以在 RecyclerView 中显示一些虚拟内容(不是来自 Room):

但是,我很难显示 Room DB 条目而不是虚拟内容。在 Arduino 中,EEPROM I/O 几乎是一个单行程序,但在 Android Room 中,这个概念上简单的任务似乎是一个代码密集且不那么前沿的挑战。这就引出了我的第一个问题:

1) 就我而言,数据库非常精简和简单,有没有比 Room 更简单的方法,使用更少的开销和类?

关于 Room 方法,我相信我非常接近。我在执行以下操作时遇到了困难:

2) 如何将 init DummyContent 中的 for 循环替换为 Room-DB 条目(来自 ViewModel 的 allJumps)?

这是我到目前为止所得到的(我没有在 ViewModel 下发布任何东西,例如 Repository 和 DAO,因为它现在不应该引起人们的兴趣):

DummyItems(由 Room DB 条目替换的虚拟内容)

object DummyContent {

    // An array of sample (dummy) items.
    val ITEMS: MutableList<DummyItem> = ArrayList()

    // A map of sample (dummy) items, by ID.
    val ITEM_MAP: MutableMap<String, DummyItem> = HashMap()

    private val COUNT = 25

    init {
        // Add some sample items.
        // TO BE REPLACED BY ROOM DB ENTRIES <----------------------------------------------------
        for (i in 1..COUNT) {
            addItem(createDummyItem(i))
        }
    }

    private fun addItem(item: DummyItem) {
        ITEMS.add(item)
        ITEM_MAP.put(item.id, item)
    }

    private fun createDummyItem(position: Int): DummyItem {
        return DummyItem(position.toString(), "Item " + position, makeDetails(position))
    }

    private fun makeDetails(position: Int): String {
        val builder = StringBuilder()
        builder.append("Details about Item: ").append(position)
        for (i in 0..position - 1) {
            builder.append("\nMore details information here.")
        }
        return builder.toString()
    }

    // A dummy item representing a piece of content.
    data class DummyItem(val id: String, val content: String, val details: String) {
        override fun toString(): String = content
    }
}

allJumps / JumpData

// allJumps is of type LiveData<List<JumpData>>

@Entity
data class JumpData (
    @PrimaryKey var jumpNumber: Int,
    var location: String?
}

视图模型

class JumpViewModel(application: Application) : AndroidViewModel(application) {

    // The ViewModel maintains a reference to the repository to get data.
    private val repository: JumpRepository
    // LiveData gives us updated words when they change.
    val allJumps: LiveData<List<JumpData>>

    init {
        // Gets reference to WordDao from WordRoomDatabase to construct
        // the correct WordRepository.
        val jumpsDao = JumpRoomDatabase.getDatabase(application, viewModelScope).jumpDao()
        repository = JumpRepository(jumpsDao)
        allJumps = repository.allJumps // OF INTEREST <----------------------------------------------------
    }

    fun insert(jump: JumpData) = viewModelScope.launch {
        repository.insert(jump)
    }

    fun getJumps() : LiveData<List<JumpData>> {
        return allJumps
    }
}

【问题讨论】:

    标签: android kotlin android-recyclerview android-room android-database


    【解决方案1】:

    您可以尝试将此添加到object DummyContent

    object DummyContent {
        val jumpsLiveData = MutableLiveData<List<JumpData>>()
    
        private val observedLiveData: LiveData<List<JumpData>>? = null
        private val dataObserver = object : Observer<List<JumpData>> {
            override fun onChanged(newList: List<JumpData>) {
                // Do something with new data set
            }
        }
        fun observeJumpsData(jumpsLiveData: LiveData<List<JumpData>>) {
            observedLiveData?.removeObserver(dataObserver)
            observedLiveData = jumpsLiveData.apply { 
                observeForever(dataObserver)
            }
        }
    }
    

    这是 viewModel 的 init 块:

    init {
            val jumpsDao = JumpRoomDatabase.getDatabase(application, viewModelScope).jumpDao()
            repository = JumpRepository(jumpsDao)
            allJumps = repository.allJumps
            DummyContent.observeJumpsData(getJumps())
        }
    

    通过此代码,DummyContent 将在ViewModel 创建后自动订阅新数据

    在“活动”中,您创建了RecyclerView,将此文本添加到onCreate 的末尾:

    override fun onCreate(savedState: Bundle?) {
      DummyContent.jumpsLiveData.observe(this, Observer {
        recyclerAdapter.changeItemsList(it)
      }
    }
    

    changeItemsList - 改变你的回收站数据的方法,我相信你已经创建了它

    【讨论】:

    • 感谢您的建议!到目前为止, RecyclerView 仍然是空的,我想这是预期的,因为我让 onChanged() 保持原样。但我仍在努力将 allJumps(来自 ViewModel)添加到列表中。你能给我一行代码吗?
    • RecyclerView 的适配器增加设置内容
    猜你喜欢
    • 2018-09-01
    • 1970-01-01
    • 2023-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多