在我删除额外的 -wal 和 -shm 文件之前,应用程序不会读取下载的 Room 数据库文件

The application does not read a downloaded Room database file until I delete the additional -wal and -shm files

到目前为止的过程:

我制作了一个数据库文件并将其上传到 Firebase 存储中,我从中将文件下载到设备中应用程序的数据文件夹中。现在通过 Room 数据库访问文件时,table 显示为空。

我尝试了不同的方法来解决这个问题,最后我发现问题出在 Room 数据库自动生成的以 -wal 和 -shm 结尾的文件上。从 Firebase 存储下载文件时,生成的主数据库文件会被覆盖,因此这不是问题。从应用程序的数据文件夹中删除 -wal 和 -shm 文件后,应用程序将显示正确的内容。

问题是:

如何让应用程序读取下载的文件而不需要删除 -wal 和 -shm 文件?或者如何让应用程序在记下下载文件中的内容后生成这些文件?

我包括将数据库复制到数据文件夹的方法。

private void downloadMasterDatabase(){
        StorageReference pathReference = storageRef.child("master database" + "/master_table");
        String masterDbPath = "/data/data/"+ getPackageName() + "/databases/master_table";
        File masterDbFile = new File(masterDbPath);
        pathReference.getFile(masterDbFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
                Toast.makeText(MainActivity.this, "download was successful" , Toast.LENGTH_SHORT).show();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(MainActivity.this, "download was not successful", Toast.LENGTH_SHORT).show();
            }
        });
    }

您在下载数据库文件之前打开了数据库,但没有关闭它。那将无法可靠地工作。请注意,这包括打开数据库,然后只允许您的应用进程终止。

因此,执行以下操作:

  • 打开数据库
  • 关闭数据库,这应该会自动删除 -wal-shm 文件
  • 确认 -wal-shm 文件不再存在
  • 用下载的副本替换数据库文件

How can I make the application read the downloaded file without needing to delete the -wal and -shm files?

那不行,抱歉。

Or how can I make the application generate those files after taking note of the contents in the downloaded file?

关闭数据库,并且那些文件不再存在,然后将下载的数据库复制到位并打开它。

FWIW,this sample project 演示了备份和恢复数据库。刚好是用本地拷贝(通过Storage Access Framework)而不是下载,不过原理是一样的