I am making an Image loader for loading images into lists - so in order it to be smooth, everything needs to run in the background thread except setting the image to the view. The problem is that the Runnable in the code bellow is sometimes not executed. I am calling the setImage method from background threads.
protected void setImage(final ImageView img, final Bitmap bm, String hash) {
img.setTag(TAG_RESPONSE, hash);
Log.v(TAG, "setting image bitmap1");
//TODO: here is the bug - sometimes the runnable below is not called
img.post(new Runnable() {
@Override
public void run() {
Log.v(TAG, "setting image bitmap2");
img.setImageBitmap(bm);
img.invalidate();
}
});
}
Anyone has any ideas what am I doing wrong?
View. post actually queues the animation on the View's message loop, so once the view gets attached to the window, it executes the animation instead of having it execute manually. Yes, the Runnable (code) is posted to a Handler which is (assumed) to be associated with the UI(main) thread.
There are two main uses for a Handler: (1) to schedule messages and runnables to be executed at some point in the future; and (2) to enqueue an action to be performed on a different thread than your own. Scheduling messages is accomplished with the post(Runnable) , postAtTime(java. lang.
According to the documentation, the post(...) should be called from non-UI threads only when the View is attached to a window. This could be the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With