Andrew Knoesen
Andrew Knoesen

Reputation: 45

Export Room database and attach to email Android Kotlin

I have the following code below for exporting a room database and then attaching it to an email. Currently the user first has to choose where they want the data saved before it can be attached.

Is there a way that I can do this without first having to ask the user where to save the database?

Here is my code:

fun exportDatabase() {
        val intent = Intent(Intent.ACTION_CREATE_DOCUMENT)
        intent.type = "*/*" // this line is a must when using ACTION_CREATE_DOCUMENT
        startActivityForResult(
            intent,
            DATABASE_EXPORT_CODE
        )
    }

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

        when (requestCode) {
            DATABASE_EXPORT_CODE -> {
                val userChosenUri = data?.data
                val inStream = getDatabasePath("app_database").inputStream()
                val outStream = userChosenUri?.let { contentResolver.openOutputStream(it) }

                inStream.use { input ->
                    outStream.use { output ->
                        output?.let { input.copyTo(it) }
                        Toast.makeText(this, "Data exported successfully", Toast.LENGTH_LONG).show()
                        val emailIntent = Intent(Intent.ACTION_SEND)
                        //Set type to email
                        emailIntent.type = "vnd.android.cursor.dir/email"
                        var toEmail: String = "[email protected]"
                        emailIntent.putExtra(Intent.EXTRA_EMAIL, toEmail)
                        emailIntent.putExtra(Intent.EXTRA_STREAM, userChosenUri)
                        emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Data for Training Log")
                        startActivity(Intent.createChooser(emailIntent, "Send Email"))
                    }
                }

            }

            else ->
                Log.d("D001", "onActivityResult: unknown request code")
        }

    }

Upvotes: 1

Views: 2494

Answers (1)

Zain
Zain

Reputation: 40840

You need to use FileProvider. But FileProvider doesn't support transferring database files directly (Check here).

This can handled with:

Solution 1:

Create a custom FileProvider class that supports copying database files:

class DBFileProvider : FileProvider {
    
    fun getDatabaseURI(c: Context, dbName: String?): Uri? {
        val file: File = c.getDatabasePath(dbName)
        return getFileUri(c, file)
    }

    private fun getFileUri(context: Context, file: File): Uri? {
        return getUriForFile(context, "com.android.example.provider", file)
    }
    
}

And request the FileProvider in manifest:

<application>

    ....

    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="com.android.example.provider"
        android:exported="false"
        android:enabled="true"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
    </provider>

</application>

And create provider_paths under res\xml

<?xml version="1.0" encoding="utf-8"?>

<paths>

    <files-path
        name="databases"
        path="../" />

</paths>

Then to send this database file through the email:

public static void backupDatabase(AppCompatActivity activity) {
    Uri uri = new DBFileProvider().getDatabaseURI(activity, "app_database.db");
    sendEmail(activity, uri);
}
private fun sendEmail(activity: AppCompatActivity, attachment: Uri) {
    val emailIntent = Intent(Intent.ACTION_SEND)
    //Set type to email
    emailIntent.type = "vnd.android.cursor.dir/email"
    val toEmail = "[email protected]"
    emailIntent.putExtra(Intent.EXTRA_EMAIL, toEmail)
    emailIntent.putExtra(Intent.EXTRA_STREAM, attachment)
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Data for Training Log")
    activity.startActivity(Intent.createChooser(emailIntent, "Send Email"))
}

Solution 2:

Copy the database file to a temp file to a directory supported by FileProvider like filesDir:

  • Get the database file using getDatabasePath
  • Copy the database file to a storage directory that is supported by FileProvider
  • Create the Uri of the new copied file using the FileProvider
fun backupDatabase(activity: AppCompatActivity) {

    // Get the database file
    val dbFile = activity.getDatabasePath("app_database.db")

    try {

        // Copy database file to a temp file in (filesDir)
        val parent = File(activity.filesDir, "databases_temp")
        val file = File(parent, "myDatabase")
        dbFile.copyTo(file)

        // Get Uri of the copied database file from filesDir to be used in email intent
        val uri = getUri(activity.applicationContext, file)

        // Send an email
        sendEmail(activity, uri)

    } catch (e: IOException) {
        e.printStackTrace()
    }
}


private fun getUri(context: Context, file: File): Uri {
    var uri = Uri.fromFile(file)

    // Using FileProvider for API >= 24
    if (Build.VERSION.SDK_INT >= 24) {
        uri = FileProvider.getUriForFile(
            context,
            "com.android.example.provider", file
        )
    }
    return uri
}

Use the same manifest of solution 1. And adjust provider_paths under res\xml with the created temp dir:

<?xml version="1.0" encoding="utf-8"?>

<paths>
    <files-path
        name="databases_temp"
        path="/" />
</paths>

N.B: In both solutions, adjust the package name to yours.

enter image description here

Upvotes: 1

Related Questions