Search code examples
androidpdfsd-cardfileprovider

Error while opening file from removable SD-Card with FileProvider Android


My goal is to open pdf file from any memory.

I use android emulator with device memory and also removable SD-Card.

So pathes look like:

/storage/emulated/0/hts221.pdf - device memory

/storage/1317-231C/LPS22HB.pdf - removable SD-Card

Using this code to open file (where fileName is one of the two above):

 File file = new File(fileName);
 Intent target = new Intent(Intent.ACTION_VIEW);
 Uri fileURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", file);
 target.setDataAndType(fileURI,"application/pdf");
 target.setFlags(target.getFlags() | Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION );
 Intent intent = Intent.createChooser(target, "Open File");
 context.startActivity(intent);

AndroidManifest.xml

<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>

xml/provier_path

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

Problem:

When I try to open pdf file from device memory (/storage/emulated/0/hts221.pdf) - Everything works fine.

But, when I try to open pdf file from SD-Card (/storage/1317-231C/LPS22HB.pdf) - Application crashes with:

W System.err: java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/1317-231C/LPS22HB.pdf
W System.err:   at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:711)
W System.err:   at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:400)

What am I missing here? I guess the problem is somewhere in xml/provier_path.

I use Qt Android, but I think this is not really matter in this case.


Solution

  • Added

     <root-path name="root" path="." />
    

    to xml/provider_path. And both files work fine now.