Search code examples
androidandroid-studioandroid-file

Where to store static pdf or general files while building an android app?


I have a number of pdf files (but I might extend the functionality to other document types as well) that I want to show in my app. Static images go in drawable folder, static text goes in the strings file. But where do I put pdf files?

I know I can host it on a server and have a one-time-download kind of thing, but for my app's use case that's impossible. The app is being designed for a very specific use case in mind and I absolutely need to bundle the pdf files along with the app.


Solution

  • I'm answering my own question because other answers didn't fully work for me.

    Like the other answers, I read the file from assets folder and created a file in internal storage. I used muPDF which works perfectly with file URI.

    items is an ArrayList of file names.

    try
    {
        AssetManager assetManager = getAssets();
        InputStream in = assetManager.open(items.get(position));
        byte[] buffer = new byte[in.available()];
        in.read(buffer);
        File targetFile = new File(getFilesDir(), items.get(position));
        OutputStream outStream = new FileOutputStream(targetFile);
        outStream.write(buffer);
        in.close();
        outStream.flush();
        outStream.close();
    
        //Change below intent statements as per your code
        Intent intent = new Intent(this, DocumentActivity.class);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.fromFile(targetFile));
        startActivity(intent);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }