This question already has an answer here:
- Read a pdf file from assets folder 7 answers
I am trying to display "NEFT.pdf" file stored in the asset folder of my android app.
The following code works absolutely fine till API 25
private void CopyReadAssets(String filename) {
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), filename);
try {
in = assetManager.open(filename);
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/"+filename), "application/pdf");
startActivity(intent);
} catch (Exception e)
{
Toast.makeText(PdfFilesList.this, "cra: "+e.toString(), Toast.LENGTH_SHORT).show();
}
}
This code does not work on API 25 and above. It gives the error MODE_WORLD_READABLE no longer supported.
I changed it to MODE_PRIVATE but that gives me another error
android.os.fileuriexposedexception exposed beyond app through intent.getdata().
So I applied the concept explained at Developer.Android.com.
This is what I get in the error log:
E/DisplayData: openFd: java.io.FileNotFoundException: No such file or directory
E/PdfLoader: Can't load file (doesn't open) Display Data [PDF : NEFT.pdf] +ContentOpenable, uri: content://com.user.plansmart.provider/pdf_files/NEFT.pdf
uri looks correct to me. Can Anyone help me in locating the error here.
Here is the provider element in the manifest file.
<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>
This is the provider_paths.xml file
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
<files-path name="pdf_files" path="pdf/"/>
This is the Android code to display the pdf file
private void displayFile(String filename) {
try {
File filePath = new File(getApplicationContext().getFilesDir(), "pdf");
File newFile = new File(filePath, filename);
//new version
Uri fileUri = FileProvider.getUriForFile(PdfFilesList.this,
BuildConfig.APPLICATION_ID + ".provider", newFile);
getApplicationContext().grantUriPermission(PACKAGE_NAME,
fileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(fileUri, "application/pdf");
intent.setFlags(FLAG_GRANT_READ_URI_PERMISSION | FLAG_GRANT_WRITE_URI_PERMISSION);
startActivity(intent);
}catch (Exception e){
e.printStackTrace();
Toast.makeText(PdfFilesList.this, "df "+e.toString(), Toast.LENGTH_SHORT).show();
}
}