android - 问题用房间数据库填充微调器 android kotlin
问题描述
我想在 kotlin 中使用房间数据库填充微调器,但微调器中的项目不同。项目的数量是真实的。正是我想在类别类中制作标题的 ArrayList并在片段中的微调器中显示它们
@Entity(tableName = "cat_table")
class Category(val title: String,
val fulType: Int,
val SaleP: Long,
val BuyP: Long,
var created: Date = Date()
) {
@PrimaryKey(autoGenerate = true)
var id: Int = 0
}`
通过这个想要在 ArrayList 中显示所有标题并设置为 spinner
private fun initData() {
val packageTypesAdapter = context?.let {ArrayAdapter<Any>(it,android.R.layout.simple_spinner_item)}
catViewModel!!.allCats.observe(viewLifecycleOwner, Observer { packageTypes ->
packageTypes?.forEach {packageTypesAdapter!!.add(it)}
})
spinner2.adapter = packageTypesAdapter
spinner2.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(adapterView: AdapterView<*>, view: View, i: Int, l: Long) {
Toast.makeText(context, "$packageTypesAdapter", Toast.LENGTH_SHORT).show()
//if (i == 0) {
// loadAllTodos()
//} else {
// val string: String = parent.getItemAtPosition(position).toString()
// loadFilteredTodos(string)
//}
}
override fun onNothingSelected(adapterView: AdapterView<*>) {
}
}
}`
如果使用此查询
@get:Query("SELECT * FROM cat_table WHERE title ")
val allCatTitle: LiveData<List<Category>>
spinner 没有什么可显示的,下面的查询就像这张图片
@get:Query("SELECT * FROM cat_table ORDER BY created DESC")
val allCatByDate: LiveData<List<Category>>
解决方案
以防其他人遇到同样的问题。这是我前一段时间的做法(Kotlin)。
道
@Query("SELECT deviceName FROM device_table WHERE deviceType = :deviceType")
fun getDevice(deviceType: String): LiveData<List<String>>
存储库
fun getDevice(deviceType: String): LiveData<List<String>> {
return deviceDao.getDevice(deviceType)
}
视图模型
fun getDevice(deviceType: String): LiveData<List<String>> {
return repository.getDevice(deviceType)
}
最后在我的片段中:
private fun initSpinnerData() {
val spinner3 = view?.findViewById<Spinner>(R.id.spinnerRecord_devices)
if (spinner3 != null) {
val allDevices = context?.let {
ArrayAdapter<Any>(it, R.layout.spinner_text)
}
mDevicesViewModel.getDevice("Appliance")
.observe(viewLifecycleOwner, { devices ->
devices?.forEach {
allDevices?.add(it)
}
})
spinner3.adapter = allDevices
spinner3.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
Toast.makeText(requireContext(), "$allDevices", Toast.LENGTH_LONG).show()
}
override fun onNothingSelected(parent: AdapterView<*>?) {
TODO("Not yet implemented")
}
}
}
}
推荐阅读
- ios - UITableViewCell 与下拉 UITableView
- angularjs - 在 AngularJS 中发生 ng-if、ng-show 等之后,我该如何做一些动作?
- spring - IgniteSpringBean 和 Ignite SpringTransactionManager 在 2.4 中不再一起工作
- javascript - 错误:找不到模块“data-service.js”
- activejdbc - ActiveJDBC 有flush吗?
- react-native - React Native Apollo client.query 没有从应用同步中获取更新的数据 - dynamo db
- javascript - 输入类型 FILE 多个 - 一个一个添加文件
- html - 带有来自 Amazon S3 的图像的 Img 标签不起作用
- php - PHP 无法在表单提交上设置会话令牌
- python - 如何在 Python 中使用值设置特定索引