Room database pitfalls
When using Room database, I found that there are conditions that require a field to be combined to write this SQL
@Query("SELECT * FROM Table name WHERE FieldsA = '1' and FieldsB <= :Time " + "and FieldsB >= :Time and FieldsC <= :BTime and FieldsC >= :BTime " + "and '(' || FieldsD is null or FieldsD = '' || ')'") List selectList(String Time, String BTime);
The "||" here is a unique expression in Room, which replaces the "+" number in Java
Normally used in android is like this
String sql = "SELECT * FROM Table name WHERE FieldsA = '1' and FieldsB <= "+Passes passed in +" " + "and FieldsB >= "+Passes passed in +" and FieldsC <= "+Passes passed in +" and Fieldsc >= "+Passes passed in +" " + "and '(' "+" FieldsD is null or FieldsD = '' "+" ')'" cursor = (sql, null);
In Room, "||" is used instead of "+"
The pitfall of Room query statement
@Query("SELECT * FROM Table name WHERE FieldsA = '0' order by id desc") List selectList();
If you are querying the content of a table, then suddenly an exception will appear
# [Android RoomDatabase Cruash "Cursor window allocation of 4194304 bytes failed"](/questions/75456123/android-roomdatabase-cruash-cursor-window-allocation-of-4194304-bytes-failed)
Break log:
: Could not allocate CursorWindow '/data/user/0//databases/' of size 2097152 due to error -13. at (Native Method) at .<init>(:139) at .<init>(:120) at (:202) at (:147) at (:140) at (SourceFile:21) at .y0(SourceFile:1) at (SourceFile:230) at (SourceFile:1) at (SourceFile:1) at $(SourceFile:42)
Trigger reason
-
Room
CorrespondingSqlite
database, itsCursorWindows
The allocation size is limited, the maximum2M
, after exceeding the above crash and crash phenomenon (sometimes appear and difficult to reproducebug
)
Solution
The business party needs to sort out this business and optimize database calls. If you know that multiple database methods will be called in one method, you need to ask the controller to provide a new method. The controller layer method needs to be added with @Transaction for annotation, so as to ensure database operations within the same thing, so as to avoid CursorWindows size exceeding 2M
Then the question is@Transaction
What is this annotation for?
translateWhat is the meaning of a business
@Transaction @Query("SELECT * FROM Table name WHERE FieldsA = '0' order by id desc") List selectList();
Then the problem is solved perfectly
This is the article about the easy problems and solutions to Android Room databases. For more information about Android Room databases, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!