[英]Android RoomDB custom update query gives android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed:
[英]RoomDb Query Returning null
我正在查询我的房间数据库以检查某个项目是否存在,但是即使该项目已在数据库中,该查询也始终返回 null。 我正在使用协程
这是我的查询
@Query("SELECT EXISTS(SELECT * FROM cart_item WHERE productId = :productId)")
suspend fun getItemCount(productId: Int): Int?
我的存储库中的函数
suspend fun getCartItemCount(productId: Int): Int? {
return coroutineScope{
cartItemDao.getItemCount(productId)
}
}
在我的视图模型中
fun getCartItemCount(productId: Int): MutableLiveData<Int>? {
var itemCount: MutableLiveData<Int>? = MutableLiveData()
launch {
itemCount!!.value = repository.getCartItemCount(productId)
}
return itemCount
}
这就是我在 Fragment 中实现它的方式
fun getCartItemCount(productId: Int){
var itemCount: Int? = null
mainViewModel!!.getCartItemCount(productId)!!.observe(viewLifecycleOwner, Observer {
itemCount = it
})
Log.d("ITEMCOUNT ----> ", " $itemCount")
}
我认为您缺少有关如何使用协程的一些基础知识。
itemCount
。 触发器从未执行过,即使执行了,它也不会执行您的日志语句。 您的视图模型使用LiveData
来发布更改,那么您需要在您的方法上返回一个值吗?
建议的更改
存储库
// repository
suspend fun getCartItemCount(productId: Int): Int? {
return cartItemDao.getItemCount(productId)
}
查看模型
var itemCount: MutableLiveData<Int> = MutableLiveData()
// maybe rename method as it's not a getter anymore
fun getCartItemCount(productId: Int) {
viewModelScope {
itemCount.value = repository.getCartItemCount(productId)
}
}
在你的片段中
fun getCartItemCount(productId: Int){
mainViewModel?.observe(viewLifecycleOwner, Observer {
itemCount = it
// this will be triggered every time the "LiveData.value" changes
// this could return null if the live data value is not set.
Log.d("ITEMCOUNT", "$it")
})
mainViewModel?.getCartItemCount(productId)
}
推荐阅读:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.