Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - No Activity found to handle Intent { act=android.intent.action.VIEW - Trying to open a PDF File

I searched a lot to find a solution , but still can't find any

I am trying to open a PDF file in my android application

Here is my code to do this :

try 
    {
        File file = new File(Environment.getExternalStorageDirectory()+"/pdf/Read.pdf");
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(file);
        Log.d("CheckingURI", uri.toString());
        intent.setDataAndType(uri, "application/pdf");
        startActivity(intent);
    } 
    catch (Exception e) 
    {
        Log.d("OpenPDFError", e.getMessage());
    }

The Tomcat Log implies that there is no activity to handle the intent

09-19 19:55:02.938: D/CheckingURI(30483): file:///mnt/sdcard/pdf/Read.pdf
09-19 19:55:02.948: D/OpenPDFError(30483): No Activity found to handle Intent { act=android.intent.action.VIEW dat=file:///mnt/sdcard/pdf/Read.pdf typ=application/pdf }

Is there any other way to do this or can i open the PDF file with another default PDF viewer? If yes, how?

Update : the main problem was that i did not install a PDF viewer application on my emulator ...

like image 576
Russell Ghana Avatar asked Sep 20 '14 14:09

Russell Ghana


2 Answers

Try this instead:

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/pdf/Read.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);

CAVEAT: The above method only work if you have a pre-installed PDF Viewer. If not, you need to install a PDF Viewer.

like image 59
ChuongPham Avatar answered Sep 23 '22 09:09

ChuongPham


You just have to popup some sort of error msg to the user if no activity was found to launch the PDF (In the error dialog you can let the user know he needs some PDF app and send him to the Play Store), though i'd suggest using this piece of code instead of the genral exception catcher you're using:

try {
    /* your code */
    ...
} catch (ActivityNotFoundException e) {
    e.printStackTrace();
}

or you can use some PDF library, like this one.

like image 23
nadavfima Avatar answered Sep 24 '22 09:09

nadavfima