Life is simple if all your data comes from packaged databases, or if all your data comes from dynamic data sources (users, servers, etc.). Things get messy when your data is a hybrid of both: partially packaged and partially dynamic.
You could put everything into one database. That database would start out being copied from an asset, with empty tables for the dynamic data. Your app would then add data to those tables using ordinary Room operations.
This works, but probably it eliminates the
fallbackToDestructiveMigration() option for dealing with database schema and content upgrades.
fallbackToDestructiveMigration() would start everything over from the now-current asset, which will once again have empty tables for the dynamic data. You would lose whatever is in the current database’s edition of those tables, and that might make the user unhappy.
Instead, you would need to use migrations to carefully update your schema and formerly-packaged content while leaving the dynamic data alone.
One workaround for this is to use separate databases: one for the packaged data and one for the dynamic data. You would have two
RoomDatabase classes with entities, DAOs, and so on. This means that changes that you make to one database, such as replacing it with the current asset via
fallbackToDestructiveMigration(), would not affect the other database.
The downside is that these databases are completely independent. You cannot have entities in one database have foreign keys to the other database, for example. Instead, anything like that would need to be implemented in application code. Depending on your database structure, this may be practical or insane.
SQLite itself has a solution for this: attached databases. The
ATTACH DATABASE command tells SQLite to work with multiple databases at once, and you can have SQL statements that pull from both of them. Used carefully, this could allow the seamless integration seen in the single-database solution while still making it easy to bulk-replace the packaged data using
Room, however, has no support for
ATTACH DATABASE at the present time.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.