For the More Curious: Solving the Image Downloading Problem

This book is here to teach you about the tools in the standard Android library. If you are open to using third-party libraries, though, 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. 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 in one line:

private class PhotoHolder extends RecyclerView.ViewHolder {
       ...
        public void bindGalleryItem(GalleryItem galleryItem) {
            Picasso.with(getActivity())
                    .load(galleryItem.getUrl())
                    .placeholder(R.drawable.bill_up_close)
                    .into(mItemImageView);
        }
        ...
}

The fluent interface requires you specify a context using with(Context). 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(…) method.

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 can remove ThumbnailDownloader if you use Picasso (you will 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 using the project structure window, 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
3.145.12.242