Home » Android » Android room database won't export all the data

Android room database won't export all the data

Posted by: admin June 15, 2020 Leave a comment


I’m trying to setup Room database backup functionality.
Problem is that sql database file doesn’t contain latest set of data in the app once downloaded. It always misses some most recent records.
Is there a proper way to export room database?
P.S. I didn’t face similar problems when handled my db with sqliteHelper, so I suppose it must have something to do with Room.

Way I’m doing it:

private fun copyAppDbToDownloadFolder(address: String) {
    val backupDB = File(address, "studioDb.db") 
    val currentDB = applicationContext.getDatabasePath(StudioDatabase.DB_NAME)
    if (currentDB.exists()) {
        val src = FileInputStream(currentDB).channel
        val dst = FileOutputStream(backupDB).channel
        dst.transferFrom(src, 0, src.size())
How to&Answers:

You need to use


in your AppDatabase.java:

private static AppDatabase sInstance;

public static AppDatabase getDatabase(final Context context) {
    if (sInstance == null) {
        synchronized (AppDatabase.class) {
            if (sInstance == null) {
                sInstance = Room.databaseBuilder(context, AppDatabase.class, DATABASE_NAME)
    return sInstance;

This method will not create db.bad and db.wal files that’s creating hindrance in exporting room db.

For exporting the DB file:

Link: Exporting db with creating folder on daily basis


I had same issue. you don’t need to copy wal (write ahead log file) it’s a temporary file. According to documentation we need to close all connection to database before importing or exporting database. This solved my problem and now i have to copy only main database file.

Example of database class:

public abstract class AppDB extends RoomDatabase {    

    private static final Object sLock = new Object();

    private static AppDB INSTANCE;

    // create new database connection
    public static AppDB getInstance(final Context context) {
        synchronized (sLock) {
            if (INSTANCE == null) {
                INSTANCE = Room.databaseBuilder(context.getApplicationContext(), AppDB.class, "packagename")                    
            return INSTANCE;

    // close database
    public static void destroyInstance(){
        if (INSTANCE.isOpen()) INSTANCE.close();
        INSTANCE = null;


I’ve solved it. When exporting (saving) sql database which you handle with Room, you have to export(and later import) both – your_database.bd and your_database.wal files. Later is a journal and afaiu keeps latest records.