FileProvider: Failed to find configured root

Issue

I have been trying to share a pdf file, I set up the FileProvider like this:

On the main manifest xml:

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

The res/xml/file_paths.xml file:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <files-path name="my_files" path="." />
</paths>

And in my code I am trying the following:

String path = root.getAbsolutePath() + "/file.pdf";
final Uri data = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID+".fileprovider", new File(path));
getApplicationContext().grantUriPermission(getApplicationContext().getPackageName(), data, Intent.FLAG_GRANT_READ_URI_PERMISSION);
final Intent intent = new Intent(Intent.ACTION_VIEW).setDataAndType(data, "application/pdf").addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
getApplicationContext().startActivity(intent);

Returns error:

     Caused by: java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/file.pdf

Solution

The documentation for FileProvider says that <files-path>:

Represents files in the files/ subdirectory of your app’s internal storage area. This subdirectory is the same as the value returned by Context.getFilesDir().

Your file is not in internal storage. It is in external storage. For that, you need an <external-path> element, not a <files-path> element.

Answered By – CommonsWare

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published