Packaged Databases

We often tend to think of databases being populated at runtime:

However, another scenario is to have the database be populated already when the app is first run, with some initial data supplied by the app developer. We will explore this sort of “packaged” database in this chapter.

Going Back In Time

Back in the chapter on full-text searching, we needed a database with something to search. There, we used the text of H. G. Wells’ “The Time Machine”. The way that we got the data into our database was:

We did this manually on the first run of the app. Our BookRepository would detect that the table was empty and arrange to import the paragraphs.

It works. It is clunky, but it works.

Room offers an alternative: packaging an entire SQLite database as an asset. We can teach Room to use that database as a starting point. Then, when we first run the app, Room will copy the database from assets/ instead of creating an empty database with our schema. So, we could prepare a database that has our paragraphs already in it and use that, rather than do all the text-file import work at runtime.

This approach eliminates the time and code necessary to do the data import. In this particular case, the app actually gets bigger, because the SQLite database (with its FTS index) is larger than the text files.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.