I am creating a PDF file and saving it in local storage. When trying to open it, it is working perfect in all devices except in Android N. I am able to open PDF file in Android N using FileProvider, but it is displaying as blank.
This is my URI
content://com.products.provider/external_storage_root/Android/data/com.products/in_17052017_170502_1_1001.pdf
This is my code
Uri path;
File pdfFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"
+ "Android" + "/" + "data" + "/" + "com.products" + "/" + file);
if (Build.VERSION.SDK_INT >= 24) {
path = FileProvider.getUriForFile(getActivity(), "com.products.provider", pdfFile);
} else {
path = Uri.fromFile(pdfFile);
}
// Setting the intent for pdf reader
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), "Can't read pdf file", Toast.LENGTH_SHORT).show();
}
This error occurs when an object in the PDF document is incomplete, or when an object is missing a key element. Frequently, the error occurs when the Web server does not download enough of the object to make it usable.
Check the file format and ensure that you have installed an appropriate app to open the file. Download and install such an app from AppGallery or Google Play Store. For example, Microsoft Office or Adobe Acrobat needs to be installed to open PDF files.
From the main acrobat screen, select Edit->Preferences. Click on the General category. Make sure to uncheck 'Show online storage when saving files' Make sure to click 'OK' (You may need to move the preferences screen to get to the OK button)
The problem is with how you are setting the flags on the intent
pdfIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Instead, try this:
pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
pdfIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Grzegorz Matyszczak's solution worked for my case. I had a very similar setup to Sabya Sachi. More specifically this line allowed me to see the PDF file (URI from FileProvider.getURIForFile call):
pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
More info on grantUriPermissions
here, under android:grantUriPermissions
section.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With