1

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


}
1

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Not to mention that assets are not files on the Android filesystem, and so new File("/assets/test.pdf") will not work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.