Elior b.y. Elior b.y. - 1 year ago 86
Android Question

updating horizontal ProgressDialog using Handler, while loading an image from the web

Is it possible to update the horizontal (determinate) ProgressDialog using Handler (I deliberately don't want to use AsyncTask), while loading an image from the web? and if so, how do I do that?

this is the try block:

URL url = new URL(link);
HttpURLConnection httpCon = (HttpURLConnection)url.openConnection();
if(httpCon.getResponseCode()!=200) return;
InputStream inputStream = httpCon.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

Answer Source

Yes, it's possible. You can pass data via Message class and get them in handleMessage(Message msg) method of Handler for example this way (msg.arg1 - downloaded bytes, msg.arg2 - total bytes to download):

final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Downloading Image ...");
progressDialog.setMessage("Download in progress ...");

final Handler downloadProgressHandler = new Handler() {
    public void handleMessage(Message msg) {
        progressDialog.setProgress(100 * msg.arg1 / msg.arg2);
        if (progressDialog.getProgress() == progressDialog.getMax()) {

new Thread(new Runnable() {
    public void run() {
        try {
            URL url = new URL("<your_url>");
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            InputStream inputStream = urlConnection.getInputStream();
            int totalSize = urlConnection.getContentLength();
            ByteArrayOutputStream receivedBytesStream = new ByteArrayOutputStream();
            int downloadedSize = 0;
            byte[] buffer = new byte[1024];
            int bufferLength = 0;
            while ((bufferLength = inputStream.read(buffer)) > 0 ) {
                receivedBytesStream.write(buffer, 0, bufferLength);
                downloadedSize += bufferLength;
                Message msg = new Message();
                msg.arg1 = downloadedSize;
                msg.arg2 = totalSize;
        } catch (IOException e) {


Or if You don't want to sent data via msg.arg1 and msg.arg2 You can create custom object and add it to message like that msg.obj = new YourCustomObjectClass() // or any other object. And You can get it in handleMessage(Message msg) method like this: YourCustomObjectClass obj = (YourCustomObjectClass) msg.obj;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download