我想在RecyclerView中显示Room Database条目。到目前为止,我已经有了“房间”骨架,可以在RecyclerView中显示一些虚拟内容(不是来自“房间”):
但是我很难显示Room DB条目而不是虚拟内容。在Arduino中,EEPROM I / O东西曾经几乎是一个单行,但是在Android Room中,此概念上容易完成的任务似乎是代码密集而不是挑战性的挑战。这使我想到了第一个问题:
1)就我而言,数据库非常苗条和简单,是否有比Room使用更少开销和更少类的方法?
关于“房间”方法,我认为我已经很接近了。我在执行以下操作时遇到困难:
2)如何用Room-DB条目(ViewModel中的allJumps)替换init DummyContent中的for循环?
这是到目前为止我得到的(我没有在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? }
ViewModel
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
}
}
我想在RecyclerView中显示会议室数据库条目。到目前为止,我已经有了Room骨架,并且可以在RecyclerView中显示一些虚拟内容(不是来自Room):但是,我很难显示Room DB ...
object DummyContent