2

I am downloading some files from the internet using the async task. For this matter I know it is very relevant to show to the user the progress so far. All my implementation of downloading the file is very successful, but the only problem is with the progress dialog, this shows a 0 percent even when the download command has been started.

This is how i do it

 // Show Dialog Box with Progress bar
  @Override
  protected Dialog onCreateDialog(int id) {
    switch (id) {
        case progress_bar_type:
            prgDialog = new ProgressDialog(this);
            prgDialog.setMessage("Downloading Mp3 file. Please wait...");
            prgDialog.setIndeterminate(false);
            prgDialog.setMax(100);
            prgDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            prgDialog.setCancelable(false);
            prgDialog.show();
            return prgDialog;
        default:
            return null;
    }
}



// Async Task Class
class DownloadMusicfromInternet extends AsyncTask<String, String, String> {

    // Show Progress bar before downloading Music
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Shows Progress Bar Dialog and then call doInBackground method
        showDialog(progress_bar_type);
    }

    // Download Music File from Internet
    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {
            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();
            // Get Music file length
            int lenghtOfFile = conection.getContentLength();
            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(),10*1024);
            // Output stream to write file in SD card
            OutputStream output = new FileOutputStream(f_url[1]);
            byte data[] = new byte[1024];
            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                // Publish the progress which triggers onProgressUpdate method
                publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                // Write data to file
                output.write(data, 0, count);
            }
            // Flush output
            output.flush();
            // Close streams
            output.close();
            input.close();
        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }
        return null;
    }

    // While Downloading Music File
    protected void onProgressUpdate(String... progress) {
        // Set progress percentage
        prgDialog.setProgress(Integer.parseInt(progress[0]));
    }

    // Once Music File is downloaded
    @Override
    protected void onPostExecute(String file_url) {
        // Dismiss the dialog after the Music file was downloaded
        dismissDialog(progress_bar_type);
        Toast.makeText(getApplicationContext(), "Download complete, playing Music", Toast.LENGTH_LONG).show();
    }
}

Please how can i make the progress move according as the downloading time is moving. Thanks for helping.

UPDATE

I think this problem is not the same as the one referred to be duplicate, the problem with mine after research is coming from the int lenghtOfFile = conection.getContentLength();

The progress is not moving because the getContentLength() always returns -1 because its unable to get the file size from the server. I have seen a lot of questions like this which are not answered. Please is there a way out? I would be grateful to know. Thanks Advance

George
  • 1,086
  • 14
  • 48
  • Possible duplicate of [Download a file with Android, and showing the progress in a ProgressDialog](http://stackoverflow.com/questions/3028306/download-a-file-with-android-and-showing-the-progress-in-a-progressdialog) – Elvis Chweya Feb 21 '16 at 01:52
  • It doesn't seem like this would be the issue, but why are you turning an int into a string and then parsing it back to an int? Why not just declare your progress indicator as Integer? – nasch Feb 21 '16 at 02:07
  • What exactly is getContentLength() returning? – Doug Stevenson Feb 21 '16 at 03:51
  • @DougStevenson I get `-1` for the `getContentLength`. Please why is it happening like that – George Feb 21 '16 at 08:35
  • @ElvisChweya Please it is not same as the one you referred to as duplicate, check my update. Thanks – George Feb 21 '16 at 15:57
  • @nasch I think the problem is from the `getContenLength` – George Feb 21 '16 at 15:58
  • @George if you don't know the length of the file you are downloading there is no chance you can set a progress bar from 0 to 100, because you simply don't know when the donwload is going to finish. In this case I would suggest using an Indeterminate progress bar. – FlyingPumba Feb 21 '16 at 16:04
  • Yes, i have set Indeterminate to true but yet the problem still persist @FlyingPumba – George Feb 21 '16 at 16:10

2 Answers2

0

As you said in a comment, getContentLength() is returning -1. This causes your progress updates to always be negative, which means the progress bar never advances. That's why it's not moving as you expect.

According to the javadoc, getContentLength() returns -1 when there is no content length header or for some reason can't be parsed as a number. In this case, you can't provide a progress meter based on a size of the file being downloaded.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • @Zahan Safallwa Please can this submission be true and if yes is there any work around. Thanks – George Feb 21 '16 at 16:01
-1

If your progress bar is set to indeterminate, then there is no need to call prgDialog.setProgress(Integer.parseInt(progress[0]));. That's probably the reason why is not showing progress.

Call prgDialog.setIndeterminate(true) when the download starts, and then prgDialog.setIndeterminate(false) when it finishes. Avoid calling setProgress when you are using an indeterminate progress bar.

EDIT: Correcttion: from offical docs calling setProgress does nothing if the bar is in indeterminate mode.

Also, you said you are setting indeterminate to true, but in the onCreateDialog method I see prgDialog.setIndeterminate(false);.

FlyingPumba
  • 1,015
  • 2
  • 15
  • 37