Java – Android opening pdf does not work

Android opening pdf does not work… here is a solution to the problem.

Android opening pdf does not work

I’ve been trying to make it work for some time. I’ve seen other questions here on how to open pdf from Android, and the general consensus is that I have my code below. Am I missing something?

    try
    {
        Uri path = Uri.parse("android.resource://com. TeamGLaDOS.DayTradeSim/" + R.raw.teamdoc);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(path, "application/pdf");
        this.startActivity(intent);
    }
    catch(ActivityNotFoundException e)
    {
        Toast.makeText(this, "No Application Available to view PDF",     Toast.LENGTH_SHORT).show();
    }

EDIT: It always throws ActivityNotFoundException and displays a toast.

The exception information is this:

android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=android.resource://com. TeamGLaDOS.DayTradeSim/2130968576 typ=application/pdf }

Edit 2: I installed a pdf application (Aldiko) and I previously launched pdf in Aldiko using another application.

Solution

Your URI is built locally to access the original resource by ID, but this does not mean that all PDF readers will use the android.resource:// data URI scheme to resolve intents.
This depends somewhat on the implementation of the PDF reader application installed on the user’s device, but many checks are more than just the mimeType set in your intent. For example, Adobe Reader will resolve any intent that has a file:// URI, a content:// URI, or no URI at all (mimeType only), but it will not resolve a URI that points directly to a resource.

To be as generic as possible, you should first copy any PDF file you want to read from the Assets/Resources to the file system (internal or external storage, it makes no difference as long as the created file is externally readable).

A quick test showed that Aldiko only responds to intents with file:// URIs and “application/pdf” mimeType, and even Adobe Reader doesn’t parse other options. So it’s your winner.

HTH

Related Problems and Solutions