How to share a pdf file using absolute path file in Andriod

300 Views Asked by At

How can i share a pdf file in android i am able to view the pdf using pdfView library from the abosolute path file so I think the path is correct but am not able to share using that same path that am using to view the pdf, i also try using toast to view the path which gives the correct path but when i try sharing the file the app crashes here is the code am using

Uri uri = Uri.fromFile(new File(arrayList.get(i).getAbsolutePath()));
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("application/pdf");

            intent.putExtra(Intent.EXTRA_SUBJECT, "");
            intent.putExtra(Intent.EXTRA_TEXT, "");
            intent.putExtra(Intent.EXTRA_STREAM, uri);

            try {
                activity.startActivity(Intent.createChooser(intent, "Share Via"));
            } catch (ActivityNotFoundException e) {
                Toast.makeText(activity, "No Sharing App Found", Toast.LENGTH_SHORT).show();
            }
``
1

There are 1 best solutions below

0
On

So Here is the finally solution that worked

First this goes into the manifest just before the closing tag of your application

        <provider
            android:name="androidx.core.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>

Then create an xml resources directory in your res folder then create the file you specified in your manifest that is provider_paths the past this inside the file

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external_files" path="."/>
</paths>

Then finally in your actual code do this

Uri uri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".provider", new File(pdf_list.get(i).getAbsolutePath()));
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("application/pdf");

            intent.putExtra(Intent.EXTRA_SUBJECT, "");
            intent.putExtra(Intent.EXTRA_TEXT, "");
            intent.putExtra(Intent.EXTRA_STREAM, uri);

            try {
                activity.startActivity(Intent.createChooser(intent, "Share Via"));
            } catch (ActivityNotFoundException e) {
                Toast.makeText(activity, "No Sharing App Found", Toast.LENGTH_SHORT).show();
            }