mmenard30
mmenard30

Reputation: 13

Viewing a local PDF file in Android Application

I am trying to create an app that will let you view a stored PDF, like a simple file reader.

I am using a Navigational Drawer Project Base and I cannot seem to get the PDF to open.

I stored a test PDF in assets/ and I have also tried in raw/. If I try it with assets/ it crashes whenever I try to open the PDF on the device, saying "Cannot display PDF (test.pdf cannot be opened).

I have tried a few ways to try and get this to work but none have prevailed, here is my code as of now:

public void onSectionAttached(int number){
    switch (number) {
        case 1:
            mTitle = getString(R.string.title_song);

            File pdfFile = new File("/assets/test.pdf");

            Uri path = Uri.fromFile(pdfFile);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(path, "application/pdf");
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            try
            {
                startActivity(intent);
            }
            catch(ActivityNotFoundException e)
            {
                Toast.makeText(MainActivity.this, "It didn't crash!", Toast.LENGTH_LONG).show();
            }



            break;

        case 2:
            mTitle = getString(R.string.title_artist);
            break;
    }


}

Upvotes: 1

Views: 594

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93589

You're starting an intent to view a file. An intent is launching another app. It doesn't have permission to view your assets, or even your private files. Copy it to somewhere it does have permission to read files from first, or you need to implement a ContentProvider and provide them access to the file.

Upvotes: 1

Related Questions