Question

The problem: I'm getting a Base64-Encoded String of raw PDF data from a web service (this data is housed in my String array pdfData). I have to use this data display the PDF in a PDF viewer (I happen to be using the included 'ThinkFree PDF Viewer' since I'm working on an Android application, but lets generalize and say any PDF viewer will do). Note that I'm accessing the 0th element of this array just for testing purposes (to make sure I can at least pull up 1 PDF before writing the code to pull up all the PDFs).

The code is within a class. First the method createFile is called, then intentOpenPDF:

import org.apache.commons.codec.binary.Base64;

File file;
FileOutputStream outputStream;
private byte[] decodedContent;
private String[] pdfData;
private String[] pdfFileName;

public void createFile() {

    decodedContent = Base64.decodeBase64(pdfData[0].getBytes());

    try {
        File path = new File(getFilesDir(), "PDFs");
        if (!path.exists()) {
            path.mkdirs();
        }
        file = new File(path, pdfFileName[0]);
        outputStream = new FileOutputStream(file);
        outputStream.write(decodedContent);
        outputStream.close();
    } 
    catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } 
    catch (IOException ex) {
        ex.printStackTrace();
    }
    finally {
        // Make absolutely certain the outputStream is closed
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

public void intentOpenPDF() {

    // Make sure the file exists before accessing it:
    if (file.exists()) {
        Uri targetUri = Uri.fromFile(file);

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(targetUri, "application/pdf");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        startActivity(intent);
    }
}

The error: Error opening file. It does not exist or cannot be read.

I have a break point set inside the conditional statement that checks if the file exists (within the intentOpenPDF method), and it IS passing this check.

Was it helpful?

Solution

The path produced by calling getFilesDir() leads a protected directory (file:///data/data/), where only files created with openFileOutput(String, int) are stored. I am not creating the file this way. The solution in my case is to use getExternalFilesDir(null).getAbsolutePath() instead, which will give you a path a directory internal to the application (/storage/emulated/0/Android/data/). No permissions are required to read or write to this path.

OTHER TIPS

Considering your error message:

It does not exist or cannot be read.

as you verified it exists (first possible cause), it's certainly not readable (second possible cause).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top