Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Save CSV File without storage permission by using file provider

Save CSV File without storage permission by using file provider.

I need Kotlin code in which CSV file save in external storage without storage permission

I need Kotlin code in which CSV file save in external storage without storage permission

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try below step once, I think it will help you.

1. Define a provider authority in your app’s AndroidManifest.xml file

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

In the above example, the authority “com.example.fileprovider” is used. You can replace this with your own unique authority.

2. Create a file_paths.xml file in your app’s res/xml folder to define the file paths that can be accessed by the file provider

<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="export" path="export/" />

In the above example, the “export” folder under the app’s private files directory is defined as a path that can be accessed by the file provider.

3. Use the FileProvider.getUriForFile() method to get a content URI for the CSV file

    val csvFile = File(getExternalFilesDir(null), "example.csv")
val fileUri = FileProvider.getUriForFile(
    applicationContext,
    "com.example.fileprovider",
    csvFile
)

In the above example, the CSV file is stored in the app’s external files directory. You can replace this with your own file path.

4. Use the obtained URI to save the CSV file

try {
    val outputStream = contentResolver.openOutputStream(fileUri)
    outputStream?.use { outputStream ->
        outputStream.write(csvData.toByteArray())
    }
} catch (e: IOException) {
    // Handle the exception
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading