【问题标题】:How to insert rows into a Room Database from another database file?如何将行从另一个数据库文件插入到房间数据库中?
【发布时间】:2021-11-19 17:53:04
【问题描述】:

我的应用程序有一个预填充的 Room 数据库,当应用程序首次启动时,它会从“Assets”文件夹复制到设备中应用程序的数据文件夹。

现在我正在研究如何在数据库文件已经存在的情况下向数据库添加行。为此,我将使用 Firebase 存储来保存“主文件”,并且需要下载主文件,然后我需要检查应用程序“数据”文件夹中的当前文件中是否存在所有行以及是否存在行丢失,然后我会将丢失的行插入复制到设备的数据库文件中。

我的问题是我不知道将“主文件”下载到哪里以及如何访问该文件的内容。我是否应该创建另一个 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();
            }
        });
    }

【问题讨论】:

    标签: android sqlite storage android-room


    【解决方案1】:

    您可以使用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/

    【讨论】:

      猜你喜欢
      • 2015-03-31
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2014-11-21
      • 2015-02-04
      • 1970-01-01
      • 2011-03-30
      • 2022-09-26
      相关资源
      最近更新 更多