FileProvider throws exception on GetUriForFile

℡╲_俬逩灬. 提交于 2019-11-27 13:57:10

I finally found good example code on how to create ContentProviders and FileProviders on https://github.com/commonsguy/cw-omnibus/tree/master/ContentProvider

The actual error in my code was that in the Manifest file I had the provider tag outside of the application tag, but it must be inside. The Manifest must look like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.company.app">
<uses-sdk android:minSdkVersion="13" />

<permission
    android:name="com.company.app.fileprovider.READ"
    android:description="@string/perm_read"
    android:label="@string/perm_read_label"/>
<uses-permission android:name="com.company.app.fileprovider.READ"/>

<application android:label="MyApp">

    <provider 
    android:name="android.support.v4.content.FileProvider" 
    android:authorities="com.company.app.fileprovider" 
    android:exported="false" 
    android:grantUriPermissions="true"
    android:readPermission="com.company.app.fileprovider.READ">
                <meta-data 
                android:name="android.support.FILE_PROVIDER_PATHS" 
                android:resource="@xml/file_paths" />
    </provider>

</application>
<uses-permission android:name="android.permission.INTERNET" />

</manifest>

In trying to set up a FileProvider for getting a PDF file that is on the device and being able to email it out, I ran into this exception as well. Reading the different answers out there - it seems a bit complicated to get the FileProvider set up correctly by hand (at least this first time around).

Finally what worked for me was to copy the components from this example into an empty new project: https://github.com/IanDarwin/Android-Cookbook-Examples/tree/master/PdfShare

Once I see it working in the standalone, then I'm able to bring in the changes to my actual project.

Specifically, here are the files to replicate:

1. AndroidManifest.xml - where all the tricky FileProvider config is

2. file_paths.xml - This is a small but important component. Looking on SO there are a variety of answers for what to put there, however only from this project did the set up work for me

3. MainActivity.java - the corresponding Java setup to work with what's configured in the manifest; and of course don't forget the associated layout file

RasenKoD

This error occurred in my case because I had passed an incorrect package name to the second parameter of GetUriForFile. I used BuildConfig.PACKAGE_NAME which resolved to android.support.multidex which is incorrect.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!