I am trying to make a PDF reader that allows the user to open a PDF file from the phone.
I start by making an intent that allows me to browse for the file
Intent openFileIntent = new Intent(Intent.ACTION_GET_CONTENT);
openFileIntent.setType("*/*");
startActivityForResult(openFileIntent, FILE_OPEN_CODE);
Here is the onActivityResult:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILE_OPEN_CODE && resultCode == RESULT_OK && data != null){
Uri selectedFile = data.getData();
try {
openFile(selectedFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Once I have the Uri, I send it to the method that opens the PDF:
public void openFile(Uri fileUri) throws IOException {
final int WIDTH = viewPDF.getWidth();
final int HEIGHT = viewPDF.getHeight();
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + fileUri.getPath();
Bitmap bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_4444);
File pdfFile = new File(filePath);
Toast.makeText(getApplicationContext(), "Opened: " + filePath, Toast.LENGTH_LONG).show();
PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY));
currentPage = 0;
Matrix matrix = viewPDF.getImageMatrix();
Rect rect = new Rect(0, 0, WIDTH, HEIGHT);
renderer.openPage(currentPage).render(bitmap, rect, matrix, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
viewPDF.setImageMatrix(matrix);
viewPDF.setImageBitmap(bitmap);
}
Now, the problem is that I get the following error:
W/System.err: java.io.FileNotFoundException: No such file or directory
I am sure that the file exist, but the path that i get from the Uri is the following
/storage/emulated/0/document/2443
2443 beign the File name I get instead of "MY_FILE.pdf" I need to be able to get the file name to open the pdf on the renderer
Also, I have declared permissions in the manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
and also manually prompted for permissions for android M and above
You are constructing a non existent and impossible filePath.
You should open an InputStream to read the file.
InputStream is = getContentResolver().openInputStream(data.getData());