Search code examples
androidandroid-7.1-nougatandroidpdfviewer

Open PDF Nougat+ (File Directory)


I can't open PDFs on Ver. Nougat+, Error after codes below.

Any other way or better way to open pdf, or how to change the path to external directory.

Codes Below:

        Intent intent = new Intent(Intent.ACTION_VIEW);
        try {
            Uri path = Uri.fromFile(files.get(position));

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                intent.setDataAndType(path, "application/pdf");
            } else {
                Uri uri = Uri.parse(String.valueOf(files.get(position)));
                File file = new File(uri.getPath());
                if (file.exists()) {
                    //File file1 = new File(getActivity().getFilesDir() + File.separator + "PDF" + File.separator + "eFSIS" + File.separator + "InspectionOrder.pdf");
                    Toast.makeText(mainActivity, file.toString(), Toast.LENGTH_SHORT).show();
                    uri = FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + ".provider", file);
                    intent.setDataAndType(uri, "application/pdf");
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                }
            }
            intent = Intent.createChooser(intent, "Open With");
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            getActivity().startActivity(intent);
        } catch (ActivityNotFoundException e) { }

Provider: (Manifest)

<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>

xml:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="internal_files" path="."/>
</paths>

Error: This error is when I use the 'file' path, java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/****/****/****/***.pdf

and when I use the 'file1' path (the one in comment), it doesn't crash but it gives me the wrong directory / path. which is at 0/Android/data/***/etc.

Can't also change the getUriForFile path to: Environment.getExternalStorageDirectory().toString() where my PDFs are saved. Will give me the first error.

TIA


Solution

  • <files-path 
    

    is for /data/data/<packagename>/files/.....

    For /storage/emulated/0/..... change to

    <external-path