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}")