Search code examples
androidandroid-room

How to store Room database in a single file?


I'm completely new to android (and stackoverflow too), and I've got a question: how (if it's possible) to store or, at least, share Room database as a single file?

There are 3 files (without extension) in "databases" folder in my app's dir: database_name, database_name-wal and database_name-shm. And in top answer of this question says that Room permanently stores database in 3 files. But here someone asks about sharing one db file. Is this possible and if yes, how? Please, tell if any details of my app configuration are needed. Thank you for your respond.


Solution

  • The database, if properly closed, will be a single file. The -wal and the -shm files are files for Write Ahead Logging.

    With WAL changes to the database are applied not to the database itself but to the -wal file. At times the changes made and stored in the -wal are applied to the database.

    If ALL of the changes are applied then the database has been fully checkpointed and the -wal file will be empty and should be deleted (along with the -shm file).

    • The -shm file is like a wal file for the -wal file, so if the -wal file is empty then the -shm file should also be empty.

    If the -wal file exists and is not empty then part of the database is in the -wal file and if omitted when copying files may result in a corrupt database.

    You have the option to use journal mode via a call to the setJournalMode when doing the build. In journal mode, the -journal file holds a log of the changes made to the database and thus the file is not part of the database and the -journal file can be omitted.

    Another way to have WAL mode and a single database file would be to create a non-room copy of the database as an SQLiteDatabase over which you would have more control (so you can avoid issues/restrictions/complication encountered with Room).