0

I have my download manager, and it work perfect if I try to download a file. But I have a problem.

I have 4 CardView in my activity and I set it onClickListener, so when I click one CardView it will download the file.

Here is the code to call the download function

cardviewR1 = findViewById(R.id.card_viewR1);
cardviewR1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pDialogDL = new ProgressDialog(this);
            pDialogDL.setMessage("A message");
            pDialogDL.setIndeterminate(true);
            pDialogDL.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialogDL.setCancelable(true);
            final DownloadTask downloadTask = new DownloadTask(this);
            downloadTask.execute(R1Holder);
            pDialogDL.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    downloadTask.cancel(true);
                }
            });
        }
    });

and here is the download function

private class DownloadTask extends AsyncTask<String, Integer, String> {

        private Context context;
        private PowerManager.WakeLock mWakeLock;

        public DownloadTask(Context context) {
            this.context = context;
        }

        @Override
        protected String doInBackground(String... sUrl) {
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            try {
                URL url = new URL(sUrl[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                // expect HTTP 200 OK, so we don't mistakenly save error report
                // instead of the file
                if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                    return "Server returned HTTP " + connection.getResponseCode()
                            + " " + connection.getResponseMessage();
                }

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

                // download the file
                input = connection.getInputStream();
                output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/"+getString(R.string.r1)+"_"+NameHolder+".zip");

                byte data[] = new byte[4096];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    // allow canceling with back button
                    if (isCancelled()) {
                        input.close();
                        return null;
                    }
                    total += count;
                    // publishing the progress....
                    if (fileLength > 0) // only if total length is known
                        publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);
                }
            } catch (Exception e) {
                return e.toString();
            } finally {
                try {
                    if (output != null)
                        output.close();
                    if (input != null)
                        input.close();
                } catch (IOException ignored) {
                }

                if (connection != null)
                    connection.disconnect();
            }
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // take CPU lock to prevent CPU from going off if the user
            // presses the power button during download
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                    getClass().getName());
            mWakeLock.acquire();
            pDialogDL.show();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            // if we get here, length is known, now set indeterminate to false
            pDialogDL.setIndeterminate(false);
            pDialogDL.setMax(100);
            pDialogDL.setProgress(progress[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            mWakeLock.release();
            pDialogDL.dismiss();
            if (result != null)
                Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
            else
                Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
        }
    }

The code work in my app, but the problem is, when I try to add second CardView which is like this

cardviewR2 = findViewById(R.id.card_viewR2);
cardviewR2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            pDialogDL = new ProgressDialog(this);
            pDialogDL.setMessage("A message");
            pDialogDL.setIndeterminate(true);
            pDialogDL.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialogDL.setCancelable(true);
            final DownloadTask downloadTask = new DownloadTask(this);
            downloadTask.execute(R2Holder);
            pDialogDL.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    downloadTask.cancel(true);
                }
            });
        }
    });

Yes it will download the second file, but it will overwrite the first file. I think the problem is right here

output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/"+getString(R.string.r1)+"_"+NameHolder+".zip");

Anyone can help me with this code? I need your help, Thanks

OperasiOps
  • 33
  • 7

1 Answers1

0

Fixed it by create a new Download Class separately in different file with activity, so the AsyncTask will be call again and again thanks

OperasiOps
  • 33
  • 7