如何从另一个数据库文件插入行到房间数据库?



我的应用程序有一个预填充的Room数据库,它是从"Assets">

应用程序第一次启动时到设备中应用程序的数据文件夹。

现在我正在研究如何添加行到数据库,如果数据库文件已经存在。为此,我将使用Firebase存储来保存"主文件"。我需要下载主文件,然后我需要检查是否所有的行都存在于应用程序的当前文件"data"文件夹,如果有任何行缺失,那么我会将缺失的行插入到复制到设备的数据库文件中。

我的问题是我不知道在哪里下载"主文件"。访问和如何访问该文件的内容。我是否应该创建另一个DAO和Room Database类来访问文件,以便我可以遍历内容并像这样添加缺失的行,或者还有其他方法吗?

目前我用这个方法复制文件

private void loadDbFromFirebase(){
StorageReference pathReference = storageRef.child("user database/" + userId + "/locations_table");
String currentDBPath = "/data/data/"+ getPackageName() + "/databases/locations_table";
// create file from the database path and convert it to a URI
File currentDbFile = new File(currentDBPath);
pathReference.getFile(currentDbFile).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();
}
});
}

您可以使用cursorrawQuery从文件中访问数据库的内容:

val database = SQLiteDatabase.openDatabase(
context.applicationInfo.dataDir.toString() + "/databases/<database_name>",
null,
SQLiteDatabase.OPEN_READONLY)
val cursor = database.rawQuery("select * from tableName", null)
cursor.use { c ->
if (c!!.moveToFirst()) {
do {
val index = c.getColumnIndex(columnName)
val value = c.getString(index)
} while (c.moveToNext())
}
}

我做了一些演示应用https://github.com/YablokovDmitry/DatabaseView/