0

I'm currently trying to download a file (Word, PDF or Image) from my server to my phone and open it after. It all works when I download an Image it shows up and is saved. When I click on a PDF File, it downloads but when I try to open it only shows a black screen with an exclamation mark. When I open it with Adobe Acrobat it shows a Toast that it cant reach the file So I have the following questions:

1) Why can't a 3rd party application has access to my downloaded file and how can I fix that?

2) Where can I save my files with what code in Order to have my files in a folder where anyone can access it? (I have no sd card) And what exactly do I have to change to what in my code?

I was working on that issue for 10h+ now and tried 5+ solutions from StackOverflow but none worked for me.

The outcommented code was another solution where none was shown after even the images because the data was not found on the device.

URL url = new URL(path);
        URLConnection urlConnection = url.openConnection();
        urlConnection.connect();


        // this will be useful to display download percentage
        // might be -1: server did not report the length
        file_length = urlConnection.getContentLength();


        /**
         * Create new Folder
         */


        File new_Folder = new File("/sdcard/MY DOWNLOADED FILES/" + subFolder);
        //File new_Folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), subFolder);
        if (!new_Folder.exists()) {

            if (!new_Folder.mkdir()) {
                return "ERROR: mkdirs() failed for directory" + new_Folder.getAbsolutePath();
            }

        } else {
            Log.i("Info:", "Folder already exists");
        }

        /**
         * Create an output file to store the file for download
         */

        inputoutput_file = new File(new_Folder, fileName);


        InputStream inputStream = new BufferedInputStream(url.openStream(), 8192);
        //this will read the information in 1 KB
        byte[] data = new byte[1024];
        int total = 0;
        int count;

        OutputStream outputStream = new FileOutputStream(inputoutput_file);

        while ((count = inputStream.read(data))!= -1){
            total+=count;

            if (file_length>0) {
                int progress = total * 100 / file_length;
                publishProgress(progress);
                outputStream.write(data, 0, count);
                Log.i("Info:", "Progress: " + Integer.toString(progress));
            }
        }

        inputStream.close();
        outputStream.close();

/*            //make the file visible
        MediaScannerConnection
                .scanFile(context, new String[] 
{inputoutput_file.getAbsolutePath()},
                        new String[] {null}, null);
*/
        return "Download Complete...";

    } catch (MalformedURLException e) {
        e.printStackTrace();
        return "ERROR MalformedURLException" + e.getMessage();
    } catch (IOException e) {
        e.printStackTrace();
        return "ERROR IOException" + e.getMessage();
    }

This is part of a class where I open my files:

switch (format) {
                        case "PDF":
                            Intent pdfIntent = new Intent();
                            pdfIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                            pdfIntent.setAction(android.content.Intent.ACTION_VIEW);
                            Uri contentPDFUri = FileProvider.getUriForFile(context,
                                    "com.ndlp.socialstudy.provider",
                                    my_clicked_file);
                            pdfIntent.setDataAndType(contentPDFUri,"application/pdf");
                            Intent intentpdfChooser = pdfIntent.createChooser(pdfIntent, "Open With");
                            try {
                                context.startActivity(intentpdfChooser);
                            } catch (ActivityNotFoundException e) {
                                Toast.makeText(context, "Please install a PDF app to view your file!", Toast.LENGTH_LONG).show();
                                // Instruct the user to install a PDF reader here, or something
                            }
                        case "Word":

                        case "Image":
                            Intent imageIntent = new Intent();
                            imageIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            imageIntent.setAction(android.content.Intent.ACTION_VIEW);
                            //Uri uri = Uri.parse("file://" + my_clicked_file.getAbsolutePath());
                            Uri contentimageUri = FileProvider.getUriForFile(context,
                                    "com.ndlp.socialstudy.provider",
                                    my_clicked_file);
                            imageIntent.setDataAndType(contentimageUri,"image/*");
                            //imageIntent.setDataAndType(Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + subFolder + "/" + fileName), "image/*");

                            context.startActivity(imageIntent);

This is part of the code where I call the Downloader or the OpenFileClass:

File my_clicked_file = new File("/sdcard/MY DOWNLOADED FILES/" + subFolder + "/" + fileName);

                if (my_clicked_file.exists()) {
                    OpenFileClass openFileClass = new OpenFileClass(context, whichFormat, my_clicked_file, fileName, subFolder);
                    openFileClass.openFile();
                }
                else {
                    FileDownloader fileDownloader = new FileDownloader(context, fileName, subFolder, whichFormat, my_clicked_file);
                    fileDownloader.execute(url);
                }
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Does anything print? Stacktrace, debug output, anything? if no, you should add it because you have to know how the code responds to it, you could be missing a permission or trying to access a directory you don't have access to or that doesn't exist – Zoe Oct 27 '17 at 06:23
  • @Zoe what do you mean? I have all permissions I could possibly need in my gradle. The directory exists because I can findit when browsing in file explorer in internal storage. And how can I manage the access of 3rd party apps? – Patrick Nadler Oct 27 '17 at 10:13
  • 1. the permissions are defined in the manifest. 2. no one else knows what permissions you have and can therefore not reproduce the issue. – Zoe Oct 27 '17 at 10:21
  • @Zoe oh my bad of cojrse i mean manifest i got write/read external storage and write/read internal storage – Patrick Nadler Oct 27 '17 at 14:15
  • Do you request the at runtime (applies to API 23+) – Zoe Oct 27 '17 at 14:56
  • I just mentioned them in manifest do I have to request them at runtime??:o @Zoe – Patrick Nadler Oct 27 '17 at 16:20
  • [Yup, starting in API 23](https://stackoverflow.com/questions/33666071/android-marshmallow-request-permission) – Zoe Oct 27 '17 at 16:47
  • when I checkSelfPermission like private boolean checkIfAlreadyhaveWritePermission() { int result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (result == PackageManager.PERMISSION_GRANTED) { return true; } else { return false; } } it returns 0.i thought you can only return denied or granted? – Patrick Nadler Oct 27 '17 at 19:33
  • @Zoe I used the second answer on your link and splitted it into two methods one for write external and one for read external – Patrick Nadler Oct 27 '17 at 19:34
  • @Zoe ahh I see so I have the permission because 0 is equal to granted. So now that I have the permission how can I actually solve my problem. I really appreciate your time to help me! – Patrick Nadler Oct 27 '17 at 19:37

1 Answers1

0

Have you mentioned fileprovider element in app manifest? If not please add the below tags:--

<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.mydomain.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
    android:name="android.support.FILE_PROVIDER_PATHS"
    android:resource="@xml/file_paths" />

For more info please follow this link

srs
  • 2,521
  • 16
  • 16