Jenson Jenson - 2 months ago 35
Android Question

Show progress value for volley file download

I need to show the progress of file download in percentage.

Currently I am using Volley library. I use

InputStreamVolleyRequest
class to make the download request and
BufferedOutputStream
to read/write the file.

How can I show the progress update in the most efficient manner?

Answer

As you have mentioned that you are using InputStreamVolleyRequest, I hope you have written the following code or something similar as well:

@Override
public void onResponse(byte[] response) {
    HashMap<String, Object> map = new HashMap<String, Object>();
    try {
        if (response!=null) {

            String content =request.responseHeaders.get("Content-Disposition")
                    .toString();
            StringTokenizer st = new StringTokenizer(content, "=");
            String[] arrTag = st.toArray();

            String filename = arrTag[1];
            filename = filename.replace(":", ".");
            Log.d("DEBUG::FILE NAME", filename);

            try{
                long lenghtOfFile = response.length;

                InputStream input = new ByteArrayInputStream(response);

                File path = Environment.getExternalStorageDirectory();
                File file = new File(path, filename);
                map.put("resume_path", file.toString());
                BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(file));
                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    output.write(data, 0, count);
                }

                output.flush();

                output.close();
                input.close();
            }catch(IOException e){
                e.printStackTrace();

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

If you have already done this, putting a progress bar is easy. get ProgressDialog object and initialise as shown below:

progressDialog = new ProgressDialog(Activity Context here);
progressDialog.setTitle("Any Title here");
progressDialog.setMessage("Downloading in Progress...");
progressDialog.setProgressStyle(progressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
progressDialog.setMax(100);
progressDialog.setProgress(0);
progressDialog.show();

Then just modify the while loop as shown below:

while ((count = input.read(data)) != -1) {
    total += count;
    output.write(data, 0, count);
    progress = (int)total*100/file_length;
    progressDialog.setProgress(progress);
}

Try this and let me know.

However let me also inform you that Volley is not suitable for heavy download. Rather I suggest you to use DownloadManager or Apache's HttpClient or even AsyncTask. They are easier to use and probably better for this purpose.

Comments