简体   繁体   中英

Android loading images to ListView AsyncTask

This is more a question of application logic and performance.

Project Setup: I have an Android ListView which inflates a layout that is more aesthetically pleasing than just simple text. In each row (7 to be exact), I have an Image that is fetched by URL.

The problem: This ListView and its data are set by an ArrayList of model objects that serve as temporary data holders. When the rows are added the model objects are then used to set the data in the specific row's UI. The issue then comes along, that when a user scrolls down on the list a row that was once viewable is now out of the user's view. When the user scrolls back up to that row, the whole process of fetching the Image then happens again.

This seems like it can be avoided by instead of passing URLs through the models then fetching the images, I should fetch the images first, then pass the bitmaps to the model, therefore when the row is visible again to the user, it does not have to re-load the image.

Is there a way to write an AsyncTask that can load 7 images successfully, or do I have to create an AsyncTask object for each image?

Everytime I go this route the application crashes...

You can use Picasso library for this task. Visit http://square.github.io/picasso/

In the adapter of your ListView, in the method getView, you can put this:

     Picasso.with(context) 
     .load(url)
     .placeholder(R.drawable.ic_launcher)
     .error(R.drawable.ic_error) 
     .resizeDimen(R.dimen.list_detail_image_size,R.dimen.list_detail_image_size)                              .centerInside()
    .into(imgView);

You dont need a AsyncTask because this library already implements itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM