1

i am trying to export a SQLiteDatabase to a file. I am using ACTION_CREATE_DOCUMENT intent to get a file. It shows me the dialog, fills out everything correctly, and the file is created with zero size. I can see the files using the file manager. Yet when I check onActivityResult the Uri passed to this method looks broken. And I get IOExceptions (file not found) when trying to create a File using Uri.path

val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
    addCategory(Intent.CATEGORY_DEFAULT)
    type = "application/x-sqlite3"
    putExtra(Intent.EXTRA_TITLE, "export.db")

    putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.DIRECTORY_DOCUMENTS)
}
startActivityForResult(intent!!,4711)

I can see the proper filename, if I press save in the dialog, I end up with Activity.RESULT_OK. But the uri look like content://com.android.providers.downloads.documents/document/26 and uri.path is /document/26 and this gives me IO Exceptions.

override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
        super.onActivityResult(requestCode, resultCode, resultData)

        if (requestCode == 4711 && resultCode == Activity.RESULT_OK) {
            resultData?.data?.also { documentUri ->

                try {
                    val db = DBBackend(context!!)
                    val dbFile = File(db.getDatabaseFilename())

                    var exportFile = File(documentUri.path)
                    exportFile.createNewFile()
                    dbFile.copyTo(exportFile)
                }
                catch( error : Exception )
                {
                    Log.e("FileError", error.toString() )
                    Toast.makeText(context!!,"error: ${error.toString()}", Toast.LENGTH_LONG).show()
                }
            }
        }
    }

This makes no sense to me. What is the proper way to get a writable file in the Downloads folder?

Thanks for any hints

pettersson
  • 317
  • 2
  • 10
  • Hi. can you please add your logcat where you where getting this exception. – WhiteSpidy. Sep 26 '20 at 13:19
  • 1
    You can find a complete working example of database import/export, in the context of Room, using `ACTION_CREATE_DOCUMENT`, in https://gitlab.com/commonsguy/cw-room/-/tree/v0.3/ImportExport. FWIW, it is covered in [this book](https://commonsware.com/Room). – CommonsWare Sep 26 '20 at 13:29
  • That is a quite normal uri. And you cannot take a part of it and use for the File class as it is no file system path. You should open an output stream for the uri and then write the database content to it. – blackapps Sep 26 '20 at 13:44

0 Answers0