'Cannot display PDF (cannot be open) in Android when I open PDF through intent

I am downloading PDF through url and after saving I am opening it through intent. But it says Cannot display PDF (cannot be open). I've granted all read and write permission also. PDF is saving successfully and I can also see in my File Manager and I can open it from there. But not from my app.

Used code=>

  private void downloadAndViewAttachment(String url) {

    String extension = url.substring(url.lastIndexOf("."));
    Log.v("extension", extension);

    fileName = url.substring(url.lastIndexOf("/"));
    fileName = fileName.replace("/", "");
    Log.v("fileName", fileName);
    final File file = new File(Environment.getExternalStoragePublicDirectory(getString(R.string.app_name)),   AppConstants.Attachments);

    AndroidNetworking.download(url, file.getPath(), AppUtils.getTimeStamp() + "_" + fileName)
            .setPriority(Priority.HIGH)
            .build()
            .setDownloadProgressListener(new DownloadProgressListener() {
                @Override
                public void onProgress(long bytesDownloaded, long totalBytes) {

                    AppUtils.showRequestDialog(mActivity);

                }
            })
            .startDownload(new DownloadListener() {
                @Override
                public void onDownloadComplete() {

                    AppUtils.hideDialog(mActivity);
                    AppUtils.showToastSort(mActivity, getString(R.string.download_succesfully));
                    openPdfFile(file.getPath() + "/" + AppUtils.getTimeStamp() + "_" + fileName);
                  

                }

                @Override
                public void onError(ANError anError) {

                    AppUtils.hideDialog(mActivity);
                    Log.v("downloadError", anError.getErrorBody());
                    Log.v("downloadError", anError.getErrorDetail());
                    Log.v("downloadError", String.valueOf(anError.getErrorCode()));
                    AppUtils.showToastSort(mActivity, getString(R.string.something_error));

                }
            });

}

private void openPdfFile(String path) {

    AppUtils.hideDialog(mActivity);

    File file = new File(path);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(file), "application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivity(intent);

}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source