Lazy loading images in ListView on Android

I implemented lazy images in my ListView . I use AsyncTask to download an image from the Internet and bind it to ImageView in UIThread.

It works, except that when scrolling through the ListView change quickly, uploaded images are sometimes snapped to the wrong elements in the list.

I think the problem is the reuse of convertView in the BaseAdapter . Any ideas to solve it?

Many thanks.

EDIT: I am posting the response as follows:

 public void setBitmap(int position, Bitmap image) { View itemView = mListView.getChildAt(position - mListView.getFirstVisiblePosition()); if (itemView != null) { ImageView itemImageView = (ImageView) itemView.findViewById(R.id.item_imageview); itemImageView.setImageBitmap(image); } } 
+6
android android-listview lazy-loading
source share
2 answers

Create a function called void setBitmap(Bitmap bitmap, int position) or similar in your adapter. Let your AsyncTask call this method when a new bitmap is available. Then this method can call notifyDataSetChanged() on the user line itself to make sure the views are updated. Keeping links to views in the adapter (even by holding them in AsyncTask) is dangerous!

+2
source share

There are two problems that arise when lazily loading images in a ListView.

  • Old images are still displayed until new ones are uploaded. It's simple, just set the ImageView on the image, loading the view or setting it invisible before starting the image loading.
  • The second problem is more difficult to solve. Imagine scrolling through your list very quickly. Now your views can be reworked before the old AsyncTask finishes loading the image. Now you have two tasks performed in the onPostExecute method to set the image to the image. Now for a short time the wrong image will be displayed until the second task is completed or, even worse, for any reason related to the network, they will not end in the order in which they were started, and you have the wrong Image rewrites the correct image. To solve this problem, you should check which image should be displayed after the task is completed. The View class uses two methods for things like this:

    setTag and getTag You can associate any object with a representation of the image that comes to your mind. In most cases, I use setTag to bind the image URL as a String to the image representation before starting the task. Now I can pass getTag to String after the task is completed and compare the URL that should be displayed with the URL I downloaded, and if necessary set only the image.

+7
source share

All Articles