Reputation: 799
I have a problem with opening a pdf that I've saved to the file system within my android application.
I have a rest call serializing a byte array from the server, I then save this byte array as my pdf file. This part works fine and I can navigate to the directory where the pdf has been saved and open it all o.k.
However when trying to open the pdf from within my application either via the default pdf viewer on my phone GS4(POLARIS Office View 5) or Adobe Reader both applications are unable to open the file. POLARIS returns a toast "This document cannot be opened" Adobe launches but then throws up The document path is not valid.
My code below for persiting my files.
private String createFile(AttachmentDTO dto) {
String fileExtention = getMimeType(dto);
File file = new File(context.getExternalFilesDir(Constants.BASE_EXTERNAL_DIRECTORY_ATTACHMENTS), dto.getId() + fileExtention);
FileOutputStream fos;
try {
Files.write(dto.getAttachment(), file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file.getPath();
}
The full path for my file is
/storage/emulated/0/Android/data/com.rsd.childcare.mobile.client/files/attachments/2.pdf
Now my assumption is that neither app can open the pdf because of permissions. However I have the following within my manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I know when declaring WRITE_EXTERNAL_STORAGE you get READ permissions as well, but in 4.2 they've added this so I thought I'd try it, but still no joy.
The other thing I "thought" was by calling "getExternalFilesDir" this gave read access to 3rd party apps to these files??!!
The code below illustrates how I'm trying to read the pdf
String filePath = Attachment.findAttachmentPath(Integer.parseInt((String) view.getContentDescription()));
File file = new File(Environment.getExternalStorageDirectory() + filePath);
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
If someone can point me in the right direction I'd be most grateful
Thanks
Upvotes: 1
Views: 5056
Reputation: 1006549
It appears that you have a bit of code duplication for determining the path -- your code for writing seems to use different code for determining the path than does your code for building the Uri
for the Intent
. Are you sure that those match?
getExternalFilesDir(Constants.BASE_EXTERNAL_DIRECTORY_ATTACHMENTS)
is used for creating the file, while getExternalStorageDirectory()
is used for the Uri
. You might want to drop in some Log
statements or breakpoints to ensure that everything is lining up as expected. Even better, you might want to consolidate this logic a bit, so you're sure that you are using the same values in both places.
Upvotes: 1