3

Below is my AsyncTask to download a PDF file from CloudBoost database. The code works and downloads the file; however, what does not work is the progress bar update because the file length returned is -1. Can someone give me a tip on how I can deal with this.

By the way loading.setProgress(progress[0]); line in the the progress update method is being initialized at the top of the class that this AsyncTask class is nested in.

class DownloadPdfFromInternet extends AsyncTask<String, Integer, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... strings) {
        int count;
        try {
            URL url = new URL(strings[0]);
            URLConnection connection = url.openConnection();
            connection.connect();
            // get length of file
            int lengthOfFile = connection.getContentLength();
            Log.d("dozer74", "LengthOf File: " + lengthOfFile);

            InputStream input = new BufferedInputStream(url.openStream(), 10 * 1024);
            OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/" + pubName);
            byte data[] = new byte[1024];
            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                publishProgress((int) (total * 100 / lengthOfFile));
                // write data to file
                output.write(data, 0, count);
            }
            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }
        return null;
    }

    protected void onProgressUpdate(Integer... progress) {
        loading.setProgress(progress[0]);
    }

    @Override
    protected void onPostExecute(String url) {
        loading.dismiss();
        openPdfFile();
    }

}
Jean Vitor
  • 893
  • 1
  • 18
  • 24
jdubicki
  • 289
  • 1
  • 6
  • 21
  • A related answer is found e.g. [here](http://stackoverflow.com/questions/32988325/android-getcontentlength-always-return-1-when-downloading-apk-file/32990226#32990226). And there are other similar questions and answers to be found on StackOverflow. – Markus Kauppinen Aug 24 '16 at 18:14
  • Aww man.. Still dealing with `URLConnection` class ? Ever heard of Retrofit: http://square.github.io/retrofit/ – Chintan Soni Aug 24 '16 at 18:35

0 Answers0