Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

android - How to reopen room database after backup

I am trying to add a backup functionality to my app by using the method i found here.

My backup function:

fun backupDatabase() {
    // close database
    val appDatabase: MyDatabase = MyDatabase.getInstance(requireActivity().application)
    appDatabase.close()

    val dbfile: File = requireContext().getDatabasePath(DATABASE_NAME)
    val sdir = File(getFilePath(requireContext(), 0), "backup")
    val fileName: String = "BACKUP_" + System.currentTimeMillis()
    val sfpath: String = sdir.path + File.separator.toString() + fileName
    if (!sdir.exists()) {
        sdir.mkdirs()
    } 
        
    val savefile = File(sfpath)
    try {
        if (savefile.createNewFile()) {
            val buffersize = 8 * 1024
            val buffer = ByteArray(buffersize)
            var bytes_read = buffersize
            val savedb: OutputStream = FileOutputStream(sfpath)
            val indb: InputStream = FileInputStream(dbfile)
            while (indb.read(buffer, 0, buffersize).also { bytes_read = it } > 0) {
                savedb.write(buffer, 0, bytes_read)
            }
            savedb.flush()
            indb.close()
            savedb.close()
        }
    } catch (e: Exception) {
        e.printStackTrace()
        Log.d(TAG, "ex: $e")
    }
}

After i call this function, the backup file is successfully created but when i try to do something with the database such as insert an item, I get this error:

E/ROOM: Invalidation tracker is initialized twice :/.
E/ROOM: Cannot run invalidation tracker. Is the db closed?

I am using Android Achitecture Components and this architecture:

enter image description here

How can I reopen my database after my backup is complete?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...