Mohamed Akl
Mohamed Akl

Reputation: 652

app crashes on trying to open a pdf file from assets

i'm trying to view a pdf file that exists in the assets folder using FileProvider and when the app runs it crashes, the error displayed is

java.lang.IllegalArgumentException: Failed to find configured root that contains /file:/android_asset/sample_books/a_walk_among_trees.pdf

my code for opening the pdf file:

mTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String bookAssetPath = "file:///android_asset" +"/"+SAMPLE_BOOKS + "/" +mTextView.getText()+".pdf";
                File file = new File(bookAssetPath);
                Uri uri = FileProvider.getUriForFile(getContext(),"com.example.akl.kibrary.FileContentProvider",file);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(uri,"application/pdf");
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                startActivity(intent);
            }
        });

the provider tag in the manifest file:

<provider android:name="android.support.v4.content.FileProvider"
              android:authorities="com.example.akl.kibrary.FileContentProvider"
              android:grantUriPermissions="true"
              android:exported="false">

        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"
             />
    </provider>

and finally provider_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <internal-path name="sample_books" 
path="file:///android_asset/sample_books/" />
</paths>

thank you in advance

Upvotes: 1

Views: 778

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007554

file:///android_asset works with WebView... and pretty much nothing else. It definitely does not work with FileProvider.

Your choices are:

  • Copy the content to a file, then serve it with FileProvider

  • Use my StreamProvider, which can serve directly from assets

  • Write your own ContentProvider for streaming from assets

Upvotes: 1

Related Questions