Android Room數(shù)據(jù)庫容易遇到的問題以及解決方法
1.Android Room 數(shù)據(jù)庫的坑
在用Room數(shù)據(jù)庫的時候 發(fā)現(xiàn)有需要一個字段的條件合到一起去寫這個SQL
@Query("SELECT * FROM 表名 WHERE 字段A = '1' and 字段B <= :Time " +
"and 字段B >= :Time and 字段C <= :BTime and 字段C >= :BTime " +
"and '(' || 字段D is null or 字段D = '' || ')'")
List selectList(String Time, String BTime);這里面的 “ ||” 是Room里面獨特的表達方式 是替代了java里面的“+”號
正常在android中 使用 是這樣的
String sql = "SELECT * FROM 表名 WHERE 字段A = '1' and 字段B <= "+傳入的參數(shù)+" " +
"and 字段B >= "+傳入的參數(shù)+" and 字段C <= "+傳入的參數(shù)+" and 字段c >= "+傳入的參數(shù)+" " +
"and '(' "+" 字段D is null or 字段D = '' "+" ')'"
cursor = db.rawQuery(sql, null);而在Room 中 用 “||” 代替了 “+”
2.Android Room 查詢語句的坑
@Query("SELECT * FROM 表名 WHERE 字段A = '0' order by id desc")
List selectList();假如你正在查詢一張表的面的內(nèi)容,然后忽然跑出來一個異常
# [Android RoomDatabase Cruash "Cursor window allocation of 4194304 bytes failed"](https://stackoverflow.com/questions/75456123/android-roomdatabase-cruash-cursor-window-allocation-of-4194304-bytes-failed)
奔潰日志:
android.database.CursorWindowAllocationException: Could not allocate CursorWindow '/data/user/0/cn.xxx.xxx/databases/xxx.db' of size 2097152 due to error -13. at android.database.CursorWindow.nativeCreate(Native Method) at android.database.CursorWindow.<init>(CursorWindow.java:139) at android.database.CursorWindow.<init>(CursorWindow.java:120) at android.database.AbstractWindowedCursor.clearOrCreateWindow(AbstractWindowedCursor.java:202) at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:147) at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:140) at yd.d.m(SourceFile:21) at cn.xxx.control.y.y0(SourceFile:1) at e5.y.p(SourceFile:230) at e5.y.l(SourceFile:1) at e5.y.E(SourceFile:1) at cn.xxx.cluster.classin.viewmodel.SessionViewModel$d.invokeSuspend(SourceFile:42)
觸發(fā)原因
Room對應(yīng)的Sqlite數(shù)據(jù)庫,其對CursorWindows分配的大小是有限制的,最大為2M,超過之后會發(fā)生上述崩潰閃退現(xiàn)象(偶現(xiàn)且難以復(fù)現(xiàn)的bug)
解決方法
需要業(yè)務(wù)方梳理這塊的業(yè)務(wù),優(yōu)化數(shù)據(jù)庫的調(diào)用,如果明確知道在一個方法里面會調(diào)用多個數(shù)據(jù)庫的方法,需要讓 controller 提供新的方法,且這個 controller 層的方法需要添加 @Transaction 進行注解,從而保證在同一個事物內(nèi)進行數(shù)據(jù)庫操作,以此避免 CursorWindows 大小超過 2M
那么問題來了 @Transaction 這個注解是干嘛的呢
翻譯 事務(wù)的意思
@Transaction
@Query("SELECT * FROM 表名 WHERE 字段A = '0' order by id desc")
List selectList();接著 問題完美解決
到此這篇關(guān)于Android Room數(shù)據(jù)庫容易遇到的問題以及解決方法的文章就介紹到這了,更多相關(guān)Android Room數(shù)據(jù)庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android Studio default not found錯誤解決辦法
這篇文章主要介紹了Android Studio gradle 編譯提示‘default not found’ 解決辦法的相關(guān)資料,需要的朋友可以參考下2017-01-01
android okhttp的基礎(chǔ)使用【入門推薦】
本文主要總結(jié)了Android著名網(wǎng)絡(luò)框架-okhttp的基礎(chǔ)使用。具有一定的參考價值,下面跟著小編一起來看下吧2017-01-01
Android編程基于Contacts讀取聯(lián)系人的方法(附demo源碼)
這篇文章主要介紹了Android編程基于Contacts讀取聯(lián)系人的方法,實例分析了Contacts讀取的實現(xiàn)方法及權(quán)限設(shè)置方法,并附帶了完整實例供讀者下載參考,需要的朋友可以參考下2015-12-12

