无法在我的应用程序中显示PDF文件

时间:2018-05-23 06:27:46

标签: android pdf android-7.0-nougat

我能够使用以下代码

从服务器(Web API)成功下载PDF文件
    HttpURLConnection connection = null;
    File file;
    File outputFile = null;
    FileOutputStream fileOutputStream = null;
    InputStream inputStream = null;
    int count;
    string filename = "xxx.pdf"
    try {
        //output path would be "/data/user/0/package.ofapplication/files/folder/"
        file = new File(interface.getFileDirectory(),"folder"); 

        if (!file.isDirectory()) file.mkdirs();

        //output would be "/data/user/0/package.ofapplication/files/folder/xxx.pdf"
        outputFile = new File(file, filename);

        URL url = new URL(getUrlMethod());
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        int fileLength = connection.getContentLength();

        inputStream = new BufferedInputStream(url.openStream());

        fileOutputStream = new FileOutputStream(outputFile);

        .......other
        .......related
        .......downloading codes

        //this would return "/data/user/0/package.ofapplication/files/folder/xxx.pdf"
        return outputFile.getPath();
    }

现在,当我尝试使用Android中的以下代码查看PDF文件时,我收到了错误。

// output path would be /data/user/0/package.ofapplication/files/folder/
File pdfFile = new File(pdfPath);

Intent pdfIntent = new Intent(Intent.ACTION_VIEW)
pdfIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
pdfIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

//this is the part where im getting an error
pdfIntent.setDataAndType(FileProvider.getUriForFile(this.getActivity(), this.getActivity().getApplicationContext().getPackageName() + ".provider",pdfFile), "application/pdf");

我从上面的代码中获得的错误消息是

  

java.lang.IllegalArgumentException:找不到配置的root   包含/data/data/package.ofapplication/files/folder/1.pdf

有人可以帮我解决这个问题,我现在哭了几个小时,但仍然无法找到方法。我也试过这个链接,但我仍然有同样的错误

  

FileProvider - IllegalArgumentException: Failed to find configured root

注意:我的provider_path

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

1 个答案:

答案 0 :(得分:1)

您似乎正在尝试将文件存储在external storage上,并将XML上的路径元素定义为<external-path internal storage,因此请尝试将XML上的路径元素更改为<external-path

<files-path

10 I love coding

更多信息。 https://developer.android.com/reference/android/support/v4/content/FileProvider