For the More Curious: Solving the Image Downloading Problem

This book is here to teach you mostly about the tools in the standard Android library. If you are open to using more third-party libraries (in addition to Retrofit and the others we have introduced), there are a few libraries that can save you a whole lot of time in various scenarios, including the image downloading work you implemented in PhotoGallery.

Admittedly, the solution you implemented in this chapter is far from perfect. And when you start to need caching, transformations, and better performance, it is natural to ask whether someone else has solved this problem before you. The answer is yes: Someone has. There are several libraries available that solve the image-loading problem. We currently use Picasso (square.github.io/​picasso) for image loading in our production applications.

Picasso lets you do everything from this chapter with just a few function calls:

    private class PhotoHolder(private val itemImageView: ImageView)
        : RecyclerView.ViewHolder(itemView) {
           ...
           fun bindGalleryItem(galleryItem: GalleryItem) {
               Picasso.get()
                      .load(galleryItem.url)
                      .placeholder(R.drawable.bill_up_close)
                      .into(itemImageView)
           }
          ...
    }

The fluent interface requires you get an instance of Picasso using get(). You can specify the URL of the image to download using load(String) and the ImageView object to load the result into using into(ImageView). There are many other configurable options, such as specifying an image to display until the requested image is fully downloaded (using placeholder(Int) or placeholder(drawable)).

In PhotoAdapter.onBindViewHolder(…), you would replace the existing code with a call through to the new bindGalleryItem(…) function.

Picasso does all of the work of ThumbnailDownloader (along with the ThumbnailDownloader.ThumbnailDownloadListener<T> callback) and the image-related work of FlickrFetchr. This means you could remove ThumbnailDownloader if you used Picasso (you would still need FlickrFetchr for downloading the JSON data). In addition to simplifying your code, Picasso supports more advanced features such as image transformations and disk caching with minimal effort on your part.

You can add Picasso to your project as a library dependency, just as you have done for other dependencies (like RecyclerView).

A downside of Picasso is that it is intentionally limited so that it can remain small. As a result, it cannot download and display animated images. If you have that need, then check out Google’s Glide library or Facebook’s Fresco library. Between the two, Glide has the smaller footprint, but Fresco has the edge on performance.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.1.158