Trying to open pdf file Android

做~自己de王妃 提交于 2019-12-11 10:12:06

问题


I'm facing this error:

E/AndroidRuntime: java.lang.IllegalArgumentException: Failed to find configured root that contains /data/data/com.mobgen.androidinterviewtest/files/LaFerrari.pdf
E/AndroidRuntime:     at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:678)
E/AndroidRuntime:     at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:377)
E/AndroidRuntime:     at com.mobgen.interview.SingleCarActivity$1.onClick(SingleCarActivity.java:92)

It's because of this line of code:

Uri uri = FileProvider.getUriForFile(SingleCarActivity.this, "be.myapplication", file);

I have followed the resources that I had found: http://developer.android.com/reference/android/support/v4/content/FileProvider.html

Open file in cache directory with ACTION_VIEW

How to use support FileProvider for sharing content to other apps?

However I still couldn't manage to fix the error that I'm having.

Below you can see my code:

SingleCarActivity.java:

File file = new File(getFilesDir(), pdf); //pdf contains "LaFerrari.pdf"
Uri uri = FileProvider.getUriForFile(SingleCarActivity.this, "be.myapplication", file);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);

AndroidManifest.xml:

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="be.myapplication"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

file_paths.xml:

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

Below you can see a screenshot of how my project structure looks like: Link: http://i.imgur.com/4dbhcKF.png


回答1:


FileProvider cannot serve assets directly, as assets are not files. Your primary choices are:

  1. Copy the asset to a file, in a location that you have configured for FileProvider. I demonstrate that sort of FileProvider configuration in this sample app, but the answers to the question from your comment do the basics of copying the asset to a file.

  2. Use my StreamProvider, which can serve assets directly, without having to make a copy.



来源:https://stackoverflow.com/questions/35120988/trying-to-open-pdf-file-android

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