【发布时间】:2021-05-21 10:02:57
【问题描述】:
我是 Room 的新手,它让我陷入了一个循环。我试图在我的 Room 数据库中获取特定数据类的特定行并编译成一个列表并将这个列表变成一个字符串,这样我就可以用它做一些事情了。我可以通过将 Room 数据库表的内容打印到控制台来做到这一点,但就是这样。
我会告诉你我拥有的code
这是我的数据类。
code.kt
@Parcelize
@Entity(tableName = "code_table")
data class code(
@PrimaryKey(autoGenerate = true)
val id: Int,
val code: String //this is the item I want to isolate
): Parcelable
我使用的 ViewModel.kt 的 sn-p。
val readAllData: LiveData<List<code>>
private val repository: respository
init {
val Dao = database.getDatabase(application).dao()
repository = respository(Dao)
readAllData = repository.readAllData
}
我使用的 repository.kt 的 sn-p。
val readAllData: LiveData<List<code>> = dao.readAllData()
我使用的 Dao.kt 的 sn-p。
@Query("SELECT * FROM code_table ORDER BY id ASC")
fun readAllData(): LiveData<List<code>>
我如何读取 Room 数据库表
private fun dbread(){
mUserViewModel = ViewModelProvider(this).get(ViewModel::class.java)
mUserViewModel.readAllData.observe(viewLifecycleOwner, Observer { user ->
var abc = user
println(abc)
})
}
这是它的输出
I/System.out: [code(id=2, code=textA), code(id=3, code=textB), code(id=4, code=textC)]
我并不是只查询code 行,但我需要将code 行中的所有数据聚合到一个字符串或JSON 数组中。所以,在这种情况下,应该是 textA、textB 和 textC(我担心我还没有说清楚)
我还尝试在Dao中执行以下操作
@Query("SELECT code FROM code_table")
fun readdb(): LiveData<List<code>>//I've tried this with lot different types within the Parentheses
这使构建失败:它说以下内容
:app:kaptDebugKotlin 1 error
java.lang.reflect.InvocationTargetException (no error message)
我猜这个错误是因为 SQL 语法关闭,但我不认为它是。
我也尝试过使用ViewModel 和repository,看看是否可以让它们只输出code 行,但无济于事。我很惊讶我是第一个发帖的人。
感谢您的宝贵时间。
【问题讨论】:
标签: android sql sqlite kotlin android-room