Given a Room database DAO like this:
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Query;
import java.util.Date;
import java.util.List;
@Dao
public interface MyDao {
@Query("SELECT * FROM MyTable")
List<MyItem> all();
@Query("SELECT * FROM MyTable WHERE date = :date AND language = :language")
MyItem byDate(Date date, String language);
}
Is there a way to have a Logger or something like that added to MyDao
so that I could see which statements are being performed. This would be really helpful during development, because I could immediately check if the functions are transformed correctly to the expected SQL statement or not.
When I have got some unknown error while inserting or updating row in room db Android does not show any error in debug console. One thing I found how to check whats happen while debug is:
Output is:
As per document of Room it performs compile time check so if your SQL statement is not valid compilation itself failed and proper error message is displayed in the log.
Also generated code is debuggable by default and can be found under below mentioned path.
This class contains implementation of your DAO you can debug this class as you debug other classes in your project. :-)
Example :
Assuming that Room uses framework's Sqlite as underlying database, the statements can be quite simply logged. The only limitation: this can be done only on emulator.
From SQLiteDebug.java:
By default, the
log.tag.SQLiteStatements
's value is not set:According to the above documentation, to set the property we have to use:
As we can see, the
VERBOSE
value was successfully set. However, if we'll re-run our application - we won't see those statements printed. To make it work, we'll have to restart all the services usingadb shell stop
and thenadb shell start
.If you'll try to do that with a regular device, you'll receive the following error (tried with Pixel XL / stock Android 9):
This is why we have to use the emulator:
The emulator will restart.
Run your application and you'll see similar Sqlite statements in logcat:
To undo the changes, use these commands:
I have been able to achieve it via a hack for Select queries. This wont work for insert/update/delete operations :)
Create a separate class
RoomLoggingHelper
as followsOr, you can download this file from here
Add this file to your Project and call it from your Room Database class as follows: Override both the
query
methods like thisDisclaimers:
try-catch
blockBlobs
There does not appear to be any hooks for that at the DAO level. There are callbacks related to database opens and upgrades, but not arbitrary stuff.
You could file a feature request, though. I agree that it could be useful. Even better would be an OkHttp-style generic interceptor framework.