Reputation: 3869
In my activity, I download several images and then display them by adding each one of them on my main layout. I tried these 3 approaches but each time my progress dialog freezes until the images are loaded:
1st approach: Using an async task: I download the images on doInBackground() and add them to the main layout onPostExecute ()
2nd: The same as above, but I add each one of the images onProgressUpdate()
3rd: Using a handler and a thread
Each time the progress dialog freezes for a few seconds (actually the whole application freezes) until the images are downloaded and displayed on the screen.
I have been trying to fix this for a long time but nothing yet. Any ideas? Here's a part of my code:
protected Integer doInBackground(Void... params) {
//...
try {
//download images
}
} catch (JSONException e) {
e.printStackTrace();
}
if (!loadTask.isCancelled()) {
//Display images
int length=imageList.size();
for (i=0; i<length; i++) {
publishProgress(i);
}
}
return 1;
}
protected void onProgressUpdate(Integer... a) {
//interaction with UI thread
int i = a[0];
ImageView im = new ImageView (MyActivity.this);
im.setImageBitmap(getRemoteImage(imageUrl));
im.setLayoutParams(Params);
im.setAdjustViewBounds(true);
im.setPadding(px2, px2, px2, px2);
im.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//...
}
});
}
Upvotes: 0
Views: 815
Reputation:
im.setImageBitmap(getRemoteImage(imageUrl));
If getRemoteImage()
does what it's name and argument suggests (downloading an image from the web), then this line is your problem, since it's executed in onProgressUpdate()
.
onProgressUpdate()
runs in the UI-thread and not in the background thread, it's supposed to do UI work when the progress changed. When you download your images here, you block the UI thread for a the amount of time it takes for the download of an image to finish. Since you loop over all images, it will hold your UI thread until all your images are downloaded.
Rather run the download in doInBackground()
(your comment at the top of the method suggests that you already do that) and pass the downloaded image over to onProgressUpdate
via the argument that publishProgress()
takes.
Upvotes: 2