I am using room framework in my Android Studio project. I'm trying to create a transaction within an interface. I've read the documentation from here: https://developer.android.com/reference/androidx/room/Transaction
I know we should create transactions in abstract classes instead of interfaces. I'm just wondering if this is possible since I already have more than a dozen interfaces in my project and don't want to rewrite them as abstract classes.
What you are trying to do is not possible in an interface because you cannot use a method with a body in an interface.
More specifically, you are trying to execute multiple statements (an UPDATE, then a DELETE), but only one statement can be executed at a time.
Your options are to define a trigger (updated, if the weight row can be determined from within the trigger) or probably more likely use an abstract class and thus use a function to execute multiple statements or use exploit methods (pass / or retrieve) SupportSQliteDatabase (using an abstract class is simpler).
Then, to take advantage of transactions, you would have a dummy @Query before the function. For example
Additional
This is a working demo, designed to be run only once, which uses all three methods.
First is
@Entities
, based on what is available in the code, but has used long to represent the date (instead of using a type converter).access
weight
@Dao
Annotated abstract class with normal abstract methods and methods with bodies (Solution 1). The insert method allows inserting some data (just one row).Now,
@Database
annotated classes (using singletons) are a little more complicated.This has a callback to add the trigger, the trigger is overly complex as it not only deletes after the update (not deleting anything), but also adds a new row to the access table showing that the TRIGGER is actually being triggered ( Solution 2).
Also, due to need of better place (or not depending on style/practice), include a function to get and use SupportSQLiteDatabase (solution 3)
To actually utilize some of the activity codes aboveMainActivity
Demo results By SppInspection
As expected the weight table is empty: -
As expected, there are 4 rows in the access table: -
Finally, the schema (i.e. sqlite_master) shows that the trigger exists (additional 3 lines had to be added): -