I need to download a image in a AsyncTask and display progress in a progressDialog, the only thing i cant manage to do here is figure out how to update the progressbar properly with a 1024 bytes step, currently i have this and it doesn’t work
class DownloadImageTask extends AsyncTask<String, Integer, Void> {
@Override
protected Void doInBackground(String... url) {
bitmap = DownloadImage(url[0]);
return null;
}
@Override
protected void onProgressUpdate(Integer... args) {
mProgressDialog.setProgress(args[0]);
}
@Override
protected void onPostExecute(Void unused) {
ImageView img = (ImageView) findViewById(R.id.img);
img.setImageBitmap(bitmap);
img.setVisibility(View.INVISIBLE);
imgInfo = "Height: " + bitmap.getWidth() + " px" + "\n" + "Width: "
+ bitmap.getHeight() + " px" + "\n" + "File Size: "
+ fileSize / 1024 + " KB" + "\n" + "Image Name: "
+ getString(R.string.img_name);
isDownloaded = true;
mProgressDialog.dismiss();
}
@Override
protected void onPreExecute() {
mProgressDialog = new ProgressDialog(AndroidActivity.this);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
private Bitmap DownloadImage(String URL) {
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
private InputStream OpenHttpConnection(String urlString)
throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
fileSize = conn.getContentLength();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
// loop with step 1kb
byte data[] = new byte[1024];
long total = 0;
int count = 0;
while ((count = in.read(data)) != -1) {
total += count;
publishProgress((int)(total*100/fileSize));
}
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
}
can someone help ?
You better return the bitmap from
doInBackgroundand take it from parameter inonPostExecute()**
EDIT :
**
Once inputstream reaches its end, you cannot read anymore data from it. You should write the
InputStreamto abyte arrayinstead and then convert the bytearray to a bitmap.