Home » Android » Android – FileProvider getUriForFile when the file is on an external SD

Android – FileProvider getUriForFile when the file is on an external SD

Posted by: admin June 15, 2020 Leave a comment

Questions:

Currently, FileProvider getUriForFile method generates IllegalArgumentException when the file is on an external SD

When the file is in the device memory (under /storage/emulated/0), it works fine.

 Uri videoUri = FileProvider.getUriForFile(this,
            getApplicationContext().getPackageName() + ".provider",
            new File(videoPath));

here videoPath had the following value :

videoPath =  /storage/extSdCard/Android/data/com.podcastcutter.debug/files/episodeMp3/TEDTalks (video)/Why you should love statistics - Alan Smith.mp4  

My Manifest file contains :

       <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>

and here the provider_paths :

<external-path name="external_files" path="."/>

How can I modify the FileProvider configuration to solve this problem?

Thanks in advance.

Exception generated:

java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/extSdCard/Android/data/com.podcastcutter.debug/files/episodeMp3/TEDTalks (video)/Why you should love statistics - Alan Smith.mp4 
android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:711)                  
android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:400)

Additional Configuration information:

compileSdkVersion 25

buildToolsVersion "23.0.3"

minSdkVersion 16

targetSdkVersion 25

support libraries version : 25.1.1   
How to&Answers:

How can I modify the FileProvider configuration to solve this problem?

You can’t. FileProvider does not support removable storage.

Answer:

I added in my provider.xml this line and works fine to get file URI from SD card:

<root-path name="external_files" path="/storage/" />

Complete xml file:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="external_files"
        path="." />
    <root-path
        name="external_files"
        path="/storage/" />
</paths>

Answer:

Your provider path is the wrong type. Your videoPath shows a path to your app’s external storage but your provider path is using external-path which links to the device root external storage. (/storage/emulated/0)

Change your provider path to be <external-files-path>...</external-files-path>