0

I am trying to open a downloaded file on listview item click in android N. It works fine below API 24, but API 24 and above, it shows "cant open file" when I try to open it. I think the file path might be incorrect, but I have tried everything I know to make it work, but it is not working. Kindly help me with this issue.

GalleryFragment.java

            /**************** Create Custom Adapter *********/
            adapter = new ItemAdapter(getActivity(), arraylist, res);

            listView.setAdapter(adapter);


            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    clickposition = position;
                    textView = (TextView) view.findViewById(R.id.txtitem);

                    imageView = (ImageView) view.findViewById(R.id.listimage);
                    if (!temp.contains(position)) {
                        url = Uri.parse(array[position][1]);
                        listitemname = array[position][0];
                        DownloadData();
                        temp.add(position);
                        complete = false;
                    }


                    if (complete && temp.contains(position)) {

//                        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(), listitemname);      //"storage/sdcard0/Android/data/triad.com.catagoriesapp/files/Download",


                        if (file.exists()) {
                            Uri uri;
                            if (Build.VERSION.SDK_INT < 24) {
                                uri = filepath[position];
                            } else {


                              String u=  (filepath[position]).getPath();
                                if (u.substring(0, 8).matches("file:///")) {
                                    u = u.substring(8);
                                }
                                if (u.substring(0, 7).matches("file://")) {
                                    u = u.substring(7);
                                }
                                   File file = new File(u);

                                uri = FileProvider.getUriForFile(getActivity(), getActivity().getApplicationContext().getPackageName() + ".provider", file);
                            }

                            Intent mpOpenintent = new Intent(Intent.ACTION_VIEW);
                            mpOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            mpOpenintent.setDataAndType(uri, "*/*");
                            try {
                                startActivity(mpOpenintent);
                            } catch (ActivityNotFoundException e) {

                            }
//                            complete = false;
                        }

                    }
                }
            });


        }
        return view;
    }


    ArrayList<Integer> temp = new ArrayList<>();

    TextView textView1;
    ImageView imageView1;
    long downloadReference;

    private long DownloadData() {

        imageView.setImageResource(R.drawable.download1);
        textView1 = textView;
        imageView1 = imageView;
        // Create request for android download manager
        downloadManager = (DownloadManager) getActivity().getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(url);
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
        request.setAllowedOverRoaming(false);
        //Setting title of request
        request.setTitle("File " + listitemname + " Downloaded");

        //Setting description of request
        request.setDescription("File " + listitemname + " download in progress.");
        request.setDestinationInExternalFilesDir(getActivity(), Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(), listitemname);
//        if (PermissionCheck.readAndWriteExternalStorage(getActivity())) {
          //  request.setDestinationInExternalPublicDir(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(), listitemname);

        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

        //Enqueue download and save into referenceId
        downloadReference = downloadManager.enqueue(request);


        return downloadReference;
    }


    @Override
    public void onStop() {

        try {
            getActivity().unregisterReceiver(downloadReceiver);

        } catch (Exception e) {
        }
        super.onStop();
    }

    @Override
    public void onResume() {
        try {
            getActivity().registerReceiver(downloadReceiver,filter);

        } catch (Exception e) {
        }
        super.onResume();
    }
  //  File[] xfilepath = new File[15];
    int clickposition;
    Uri path;
    File file;
    boolean complete = false;
    DownloadManager downloadManager;
    Cursor c;
    DownloadManager.Query query;
    String apkUri;
    Uri[] filepath = new Uri[15];
    private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {


            if (imageView1 == null) {
                return;
            }

            String action = intent.getAction();

            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                complete = true;
                long downloadId = intent.getLongExtra(
                        DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                imageView1.setVisibility(View.GONE);
                textView1.setVisibility(View.VISIBLE);

                if (Build.VERSION.SDK_INT < 24) {
                    query = new DownloadManager.Query();
                    query.setFilterById(downloadReference);


                    c = downloadManager.query(query);

                    if (c != null && c.getCount() > 0) {
                        if (c.moveToFirst()) {

                            int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                            if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {

                                apkUri = c.getString(1);


                                file = new File(apkUri);

                                path = Uri.fromFile(file);
                                filepath[clickposition] = path;
                                ///add
                            }


                        }
                    }
                } else {


                        //Your read write code.

                        query = new DownloadManager.Query();
                        query.setFilterById(downloadReference);
                        c = downloadManager.query(query);
                        if (c.moveToFirst()) {
                            int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                            if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
                                apkUri = c.getString(8);//.substring(8,c.getString(8).length());///
//
                                if (apkUri.substring(0, 8).matches("file:///")) {
                                    apkUri = apkUri.substring(8);
                                }
                                if (apkUri.substring(0, 7).matches("file://")) {
                                    apkUri = apkUri.substring(7);
                                }
                                file = new File(apkUri);
                              path = Uri.fromFile(file);
                            //    path  = FileProvider.getUriForFile(getActivity(), getActivity().getApplicationContext().getPackageName() + ".provider", file);

                                filepath[clickposition] = path;
                                if (!file.exists()) {
                                    return;
                                }
                              //  getActivity().unregisterReceiver(downloadReceiver);
                            }

                        }

                    }
                }
            }




    };


    public void setListData(String array[][], int listlength) {

        for (int i = 0; i < listlength; i++) {

            final ItemModel item = new ItemModel();

            /******* Firstly take data in model object ******/
            item.setName(array[i][0]);


            /******** Take Model Object in ArrayList **********/
            arraylist.add(item);


        }

    }


}

And here is my provider_paths.xml-

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path path="Android/data/triad.com.catagoriesapp/" name="files_root" />
    <external-path path="." name="external_storage_root" />
</paths>
ankit jad
  • 1
  • 3
  • `I think the file path might be incorrect, ` Well what is the path exactly? – greenapps Jan 02 '18 at 09:11
  • And how is it that you try to open the file? Please tell what you do before you dump code and ask. – greenapps Jan 02 '18 at 09:13
  • Okay now i have deleted the unnecessary code. i am getting the uri of the item clicked in an array named "filepath". that happens in the broadcast reciever. then in the listview itemclick im uring the uri to start the intent. the value of uri in the filepath at the clicked position is - "file:///storage/emulated/0/Android/data/triad.com.catagoriesapp/files/storage/emulated/0/Download/thermo_246_big.jpg" – ankit jad Jan 02 '18 at 09:28
  • but the value of uri in the listview clicklister that is to be intent-opened is - "content://triad.com.catagoriesapp.provider/files_root/files/storage/emulated/0/Download/thermo_246_big.jpg" i cant seem to get my way around this – ankit jad Jan 02 '18 at 09:31
  • Possibly duplicate with https://stackoverflow.com/questions/38200282/android-os-fileuriexposedexception-file-storage-emulated-0-test-txt-exposed – Cao Minh Vu Jan 02 '18 at 10:07
  • No its not a duplicate of this question. – ankit jad Jan 02 '18 at 10:14
  • `it shows "cant open file"` It is all so unclear. Who is showing that? – greenapps Jan 02 '18 at 10:21
  • `File file = new File(u);`. It is all so unclear. What is the exact value of `u` at that moment? You can place such values as comment in your post. Makes all much better readable and easier to follow. – greenapps Jan 02 '18 at 10:22
  • You told noting about what happens using your Intent.ACTION_VIEW – greenapps Jan 02 '18 at 10:24
  • `uri = FileProvider.getUriForF.....`. Please tell the values of `uri.getPath()` and `uri.toString()` at that moment. – greenapps Jan 02 '18 at 10:25
  • uri.getPath() = /files_root/files/storage/emulated/0/Download/thermo_246_big.jpg uri.toString() = content://triad.com.catagoriesapp.provider/files_root/files/storage/emulated/0/Download/thermo_246_big.jpg – ankit jad Jan 05 '18 at 12:01
  • the "cant open file" is shown by the "photos" default app. the app that is used to open the jpg file i am downloading. it opens the file fine on lollipop. – ankit jad Jan 05 '18 at 12:04
  • the value of "file" in "file = new File(apkUri)" is storage/emulated/0/Android/data/triad.com.catagoriesapp/files/storage/emulated/0/Download/thermo_mc_246 (2).pdf – ankit jad Jan 05 '18 at 12:24

0 Answers0