Kotlin中使用Room數(shù)據(jù)的一個(gè)小問(wèn)題處理

Kotlin中使用Room數(shù)據(jù)的一個(gè)小問(wèn)題處理

隨手記錄一個(gè)播放器 APP 中其他同事操作數(shù)據(jù)庫(kù)處理的問(wèn)題

前置資料:

kotlin版Room數(shù)據(jù)庫(kù) — 基本使用

Android kotlin+協(xié)程+Room數(shù)據(jù)庫(kù)的簡(jiǎn)單使用Android腳本之家

sqlite常用的命令-增刪改查 - maxiongying - 博客園

背景:播放器中緩存數(shù)據(jù)庫(kù)記錄播放片源的播放位置,用于記錄斷點(diǎn)播放的位置

實(shí)現(xiàn):

1、根據(jù)片源路徑判斷數(shù)據(jù)庫(kù)表中是否存在

2、如果不存在,則在數(shù)據(jù)庫(kù)表中新建插入

3、播放過(guò)程中定時(shí)更新表中位置

1跟2的代碼邏輯如下

        currentRecent = withContext(bgContext) {
            recentDao.queryByName(videoUri!!.path)
        }
        if (currentRecent == null) {
            currentRecent = Recent(id = null ,name = videoUri!!.path, position = 0)
            supervisorScope {
                try {
                    withContext(bgContext) {
                        if(recentDao.getCount() >= 100){
                            //if total over 100 , delete earliest 50
                            recentDao.deleteInfo(50)
                        }
                        recentDao.insert(currentRecent!!)
                    }
                } catch (t: Throwable) {
                    Log.e(LOG_TAG, "recentDao.insert${t.message}")
                }
            }
        }

3的代碼如下

recentDao.updateRecent(currentRecent!!)

問(wèn)題:第一次播放新建行后無(wú)法更新表中的位置,即第3步的更新是無(wú)效的

處理方法:

new Recent雖然插入了數(shù)據(jù)庫(kù)表中,但是實(shí)際操作的并不是數(shù)據(jù)庫(kù)表中持有的,重新獲取下即可了


         if (currentRecent == null) {
-            currentRecent = Recent(id = null ,name = videoUri!!.path, position = 0)
+            var recent = Recent(id = null ,name = videoUri!!.path, position = 0)
             supervisorScope {
                 try {
                     withContext(bgContext) {
                         if(recentDao.getCount() >= 100){//if total over 100 , delete earliest 50
                             recentDao.deleteInfo(50)
                         }
-                        recentDao.insert(currentRecent!!)
+                        recentDao.insert(recent!!)
+                        currentRecent = withContext(bgContext) {
+                            recentDao.queryByName(videoUri!!.path)
+                        }
                     }
                 } catch (t: Throwable) {
                     Log.e(LOG_TAG, "recentDao.insert${t.message}")

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容