Problems opening pdf in Android: Invalid file path

I need to open a pdf file from my android application. I have a PDF saved in the application package folder (/data/data/com.app.example/files). I installed the adobe reader app in android emulator. The problem is that when I try to open a PDF file using an adobe reader, the emulator will show me the following message: Invalid file path.

I do not know why this is happening, but I am stuck on this issue. The file is saved correctly because I can open it on my computer.

Here is the code:

HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); try { HttpResponse response = client.execute(request); request(response, file_name); File file = new File("data/data/com.app.example/files/"+file_name); PackageManager packageManager = getPackageManager(); Intent testIntent = new Intent(Intent.ACTION_VIEW); testIntent.setType("application/pdf"); List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY); if(file.exists()) { if (list.size() > 0 && file.isFile()) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); Uri uri = Uri.fromFile(file); intent.setDataAndType(uri, "application/pdf"); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); }else { System.out.println("NO APPs TO OPEN PDFs."); } } else { System.out.println("FILE DOES NOT EXIST."); } }catch(Exception ex){ System.out.println("Failed!"); ex.printStackTrace(); } public String request(HttpResponse response, String file){ String result = ""; try{ InputStream in = response.getEntity().getContent(); FileOutputStream f = openFileOutput(file, MODE_WORLD_WRITEABLE); byte[] buffer = new byte[in.toString().length()]; int len1 = 0; int counter = 0; while ((len1 = in.read(buffer)) > 0) { f.write(buffer, 0, len1); counter++; } f.close(); } catch(Exception ex){ result = "Error"; } return result; } 

Thanks in advance.

Regards, Javi.

+1
source share
2 answers

This is because the PDF file is in your own package and Adobe Reader, trying to access the PDF file from your package, which is not allowed for Android application development.

You can try to save the file to sdcard and then open it

+4
source

Do not use the direct path to access files in the application that are private to your application. Use instead

 FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); 

Contact: http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

+1
source

Source: https://habr.com/ru/post/1394853/


All Articles