Search code examples
androidandroid-room

how to correctly backup room database


I read Backup Room database but I think answers contains errors for new releases of android studio and I want to know how to correctly backup and restore room database in 2022 in kotlin or java.


Solution

  • Finally, I found a solution. Database has 3 files that I have to save those files for backup:

    val dbName = RoomDb.DATABASENAME
    val documentFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) 
    when (item.itemId) {
        R.id.mnuBackup -> {
            val db = getDatabasePath(dbName).absolutePath
            val wal = getDatabasePath("$dbName-wal").absolutePath
            val shm = getDatabasePath("$dbName-shm").absolutePath
            File(db).copyTo(File(documentFolder, "$dbName"), true)
            File(wal).copyTo(File(documentFolder, "$dbName-wal"), true)
            File(shm).copyTo(File(documentFolder, "$dbName-shm"), true)
        }
        R.id.mnuRestore -> {
            val dbExternal = "$documentFolder/$dbName"
            val walExternal = "$documentFolder/$dbName-wal"
            val shmExternal = "$documentFolder/$dbName-shm"
    
            val db = getDatabasePath("$dbName").absolutePath
            val wal = getDatabasePath("$dbName-wal").absolutePath
            val shm = getDatabasePath("$dbName-shm").absolutePath
            File(dbExternal).copyTo(File(db), true)
            File(walExternal).copyTo(File(wal), true)
            File(shmExternal).copyTo(File(shm), true)
        }
        else -> {
    
        }
    }