从Intent.ACTION_CREATE_DOCUMENT Uri创建数据库

时间:2019-12-24 13:56:04

标签: android android-intent android-sqlite android-external-storage

我实际上是根据Here提出这个问题的,因为我无法在此处发表评论。我使用this答案来尝试一些操作,但是实现依赖于从scatch构建文件路径。我想知道是否有一种方法以及如何从ACTION_CREATE_DOCUMENT返回的Uri中构建数据库

到目前为止,我已经能够从onActivityResult获取Uri,但是将其传递给数据库创建者会引发错误。

下面是我的代码示例。

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if (requestCode == REQUEST_CREATE_FILE && resultCode == Activity.RESULT_OK){
        uri = data?.data

        val backupTask = BackupTask(this, null, uri!!.path, getFileName(uri!!))
        backupTask.execute()
    }
    super.onActivityResult(requestCode, resultCode, data)
}

    BackUpTask.doInBackground {
       //i've eliminated unneccessary AsyncTask codes here
       val customContext = DBContext(filePath, contextWeakReference.get())
       val dbh = DBH1(customContext, dbFileName)
    }
class DBContext(private val dbFilePath: String, base: Context?) : ContextWrapper(base){
       override fun getDatabasePath(name: String?): File {
           // **is there a way i can use the uri here?? instead of name?**
           val result = File(name)
           return result
       }

       override fun openOrCreateDatabase(name: String?, mode: Int, factory: SQLiteDatabase.CursorFactory?, errorHandler: DatabaseErrorHandler?): SQLiteDatabase {
           return openOrCreateDatabase(name, mode, factory)
       }

       override fun openOrCreateDatabase(name: String?, mode: Int, factory: SQLiteDatabase.CursorFactory?): SQLiteDatabase {
           val result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(dbFilePath), null)
           return result
       }
   }

当我尝试创建/访问数据库时,运行应用最终崩溃

Failed to open database '/document/home:file_backup.db (1)'.
    android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

0 个答案:

没有答案