[英]Room database not updating values
我有一個啟用了拖放功能的 recyclerview。
當我重新排序項目時,我試圖保存項目的交換位置。
這是我的 ontouch 聽眾。
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
// Notify your adapter that an item is moved from x position to y position
mOrderChanged = true
val from = viewHolder.absoluteAdapterPosition
val to = target.absoluteAdapterPosition
updatePos.invoke(
UpdatePos(
fromId = cps[from].id,
fromPos = from,
toId = cps[to].id,
toPos = to
)
)
updatePos
是一個監聽器,監聽器觸發片段中的以下代碼。
{ updateData ->
vm.swapCpPosition(
updateData.fromId, updateData.fromPos, updateData.toId, updateData.toPos
)
}
swapCpPosition
看起來像這樣
fun swapCpPosition(fromID : Long,fromPos:Int,toID:Long,toPos:Int){
viewModelScope.launch {
dailyChartRepo.swapCpPosition(fromID, fromPos, toID, toPos)
}
}
回購中的dailyChartRepo.swapCpPosition
:
suspend fun swapCpPosition(fromID : Long,fromPos:Int,toID:Long,toPos:Int){
dailyChartDao.swapCpPosition(fromID,fromPos,toID,toPos)
}
dailyChartDao.swapCpPosition
中的dailyChartDao.swapCpPosition
:
@Query("update cp_view_group set position =:pos where cp_id=:cpID")
fun setCpPosition(pos: Int, cpID: Long){
Timber.i("room: pos $pos id $cpID")
}
@Transaction
suspend fun swapCpPosition(fromID: Long, fromPos: Int, toID: Long, toPos: Int) {
setCpPosition((toPos+1), fromID)
setCpPosition((fromPos+1), toID)
}
正在根據日志執行查詢
2021-10-25 12:26:58.368 26091-26180/in_.co.iptech.purusharth I/mpurusharth_DailyChartDaoNew$DefaultImpls: room: pos 1 id 1633341941324
2021-10-25 12:26:58.369 26091-26180/in_.co.iptech.purusharth I/mpurusharth_DailyChartDaoNew$DefaultImpls: room: pos 2 id 17
在列表中 id 17
是第一項,id 1633341941324
是初始項位置。
然而,位置值沒有保存在數據庫中,id 17
的位置仍然是1
, id 1633341941324
仍然是數字 2
我錯過了什么,為什么值沒有更新?
這是插入您的模型
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertData(data: yourModel)
獲取想要更新的項目)
@Query("select * from table where id=:id")
suspend fun getData(id: Int): your model?
然后使用事務和更新
@Transaction
suspend fun updateData(id: Int, name:String) {
val data: yourModel? = getData(id)
if (data!= null) {
data.title= name
insertData(data)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.