Cloudinary Blog

Integrating Cloudinary With Download Adapters for Android

Add Cloudinary Directly into Android Download Adapters

Adding code to display an image in your application is one of the most common tasks for almost every application developer. However, when it comes to Android applications, there is no inbuilt support for any image related tasks, which could be a potential pain when Android developers need to handle loading (and reloading) images into the view, handling the caching and memory issues, and supporting simple UI functionality.

Gratifyingly, there are quite a few image loading and caching libraries available to choose from that take care of most of the functionality required in order to support images in an Android application. The main players in this field that are used by most image-displaying apps out there are:

Practically any application that displays images uses one of these three libraries, and even though they are not identical, their base offering is very similar, as is the API/workflow:

  • Create a download request (either a remote URL or a local file or resource).
  • Get the resource and cache it in memory and the file system.
  • Display the resource directly in an ImageView.

Since these libraries are well known, reliable, performant and rich with features, Cloudinary has seen no reason to create a full-blown download library of its own, but rather offers a means to integrate Cloudinary with the existing libraries. Android developers can use familiar workflows while still benefiting from Cloudinary's extensive selection of dynamic transformations and responsive images, as well as using a more fluent API.

The Glide Extension

For developers that already use the Glide library for their images, Cloudinary offers a quick and simple way to integrate Cloudinary functionality within existing code. Since Glide supports extensions using code-generation, Cloudinary has developed a small extension that allows developers to insert a CloudinaryRequest directly into the standard Glide pipeline, instead of sending a URL or a bitmap:

Copy to clipboard
GlideApp.with(imageView)
       .load(new CloudinaryRequest.Builder(sample)
               .transformation(new Transformation().effect(blur))
               .responsive(AUTO_FILL)
               .build())
       .into(imageView);

In the example above, a single call takes advantage of Cloudinary’s dynamic URL generation feature, applying a transformation (blur effect) and fetching an image of the appropriate size by using the runtime dimensions of the ImageView, and in this way applying client-side responsiveness on a per-device basis. Each device downloads an image that fits exactly within the available viewing area, and no bandwidth is wasted delivering a high resolution image to all devices that is then scaled down on the client side.

For comparison, achieving the same behavior without the Glide extension would require a few more complicated procedures:

Copy to clipboard
// construct a callback to load the image using glide
ResponsiveUrl.Callback callback = new ResponsiveUrl.Callback() {
   @Override
   public void onUrlReady(Url url) {
       GlideApp.with(imageView).load(url.generate()).into(holder.imageView);
   }
};

// create the URL to base the responsive image on:
Url baseUrl = MediaManager.get().url().publicId("sample").transformation(new Transformation().effect("blur"));

// call the responsive mechanism with the URL and callback to start the download:
MediaManager.get().responsiveUrl(AUTO_FILL).generate(baseUrl, holder.imageView, callback);

The Cloudinary Download Adapter

Cloudinary has also developed an adapter for a more general solution, regardless of what third-party download-library is used. The Cloudinary download adapter allows you to use a unified Cloudinary API to download and display images, and the API is very similar to the familiar workflow of the different download libraries. Implementing the adapter should almost be a drop-in replacement to your existing code.

The first step is implemented when initializing the MediaLibrary, where you select which library to use and specify it using a single line of code, for example for Glide:

Copy to clipboard
MediaManager.get().setDownloadRequestBuilderFactory(new GlideDownloadRequestBuilderFactory());

The following example using the Cloudinary adapter achieves the same result as showcased in the Glide extension example above:

Copy to clipboard
MediaManager.get().download(context)
       .load("sample")
       .transformation(new Transformation().effect("blur"))
       .responsive(AUTO_FILL)
       .into(imageView)

This approach has several benefits:

  • It uses the same Cloudinary entry point anywhere in the application where images are handled - both upload and download operations are handled using the same classes.
  • The adapter serves as an abstraction of the actual download library used, and makes it very easy to experiment with different downloaders by replacing just one line of initialization code.
  • It opens the door to many great features such as smarter content-aware caching, seamless transitions between server-side editing, client side post-processing, and more.

Adapting the Adapter

The Cloudinary download adapter ships with built-in integrations to the most popular download libraries, Picasso, Glide and Fresco. However, if required, a custom bridge class can be implemented to connect the adapter to any download library. The bridging classes are pretty small (for comparison, for Glide the entire class is under 40 lines of code):

Copy to clipboard
class GlideDownloadRequestBuilderStrategy implements DownloadRequestBuilderStrategy {

   // in most cases a private reference to the library's request builder needs 
   // to be kept. in this case, a glide Request builder instance:
   private RequestBuilder<Drawable> requestBuilder;

   // As most 3rd party requests builders need a context, a context is passed 
   // to the builder
   GlideDownloadRequestBuilderStrategy(Context context) {
       requestBuilder = Glide.with(context).asDrawable();
   }

   // load is the standard entry point to begin a download - here we delegate the
   // request url/resource (depending on the overload) to the internal builder:
   @Override
   public DownloadRequestBuilderStrategy load(String url) {
       requestBuilder.load(url);
       return this;
   }

   // and again delegate each type to the builder:
   @Override
   public DownloadRequestBuilderStrategy load(int resourceId) {
       requestBuilder.load(resourceId);
       return this;
   }

   @Override
   public DownloadRequestBuilderStrategy placeholder(int resourceId) {
       requestBuilder.placeholder(resourceId);
       return this;
   }

   // In case a callback is needed (for instance to stop a progress bar, or to
   // notify the user of errors), this is how the callback handler is delegated 
   // to the 3rd party request:
   @Override
   public DownloadRequestBuilderStrategy callback(final DownloadRequestCallback callback) {
       // register to the internal request callback mechanism, and delegate the 
       // events to our own callback passed here as an argument:
       requestBuilder.listener(new RequestListener<Drawable>() {
           @Override
           public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
               callback.onFailure(e);
               return false;
           }
           @Override
           public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
               callback.onSuccess();
               return false;
           }
       });
       return this;
   }

   // this is where the loaded resource is displayed on the image view - again, 
   // simply delegate the call to the internal instance's appropriate 
   // method (RequestBuilder.into() in this case).
   @Override
   public DownloadRequestStrategy into(ImageView imageView) {
       ViewTarget<ImageView, Drawable> target = requestBuilder.into(imageView);
       return new GlideDownloadRequestStrategy(target);
   }
}

The Bottom Line

Cloudinary now offers two new ways to easily implement Cloudinary transformations and client-side responsiveness in your Android application: an extension for integrating with Glide, and an adapter for providing in-built integration with almost any third-party Android download library, with support for Glide, Fresco and Picasso out of the box. Take advantage of Cloudinary's extensive transformations and easily implement responsiveness in your Android application. See the documentation for all the details, and give it a try today!

Recent Blog Posts

Our $2B Valuation

By
Blackstone Growth Invests in Cloudinary

When we started our journey in 2012, we were looking to improve our lives as developers by making it easier for us to handle the arduous tasks of handling images and videos in our code. That initial line of developer code has evolved into a full suite of media experience solutions driven by a mission that gradually revealed itself over the course of the past 10 years: help companies unleash the full potential of their media to create the most engaging visual experiences.

Read more
Direct-to-Consumer E-Commerce Requires Compelling Visual Experiences

When brands like you adopt a direct–to-consumer (DTC) e-commerce approach with no involvement of retailers or marketplaces, you gain direct and timely insight into evolving shopping behaviors. Accordingly, you can accommodate shoppers’ preferences by continually adjusting your product offering and interspersing the shopping journey with moments of excitement and intrigue. Opportunities abound for you to cultivate engaging customer relationships.

Read more
Automatically Translating Videos for an International Audience

No matter your business focus—public service, B2B integration, recruitment—multimedia, in particular video, is remarkably effective in communicating with the audience. Before, making video accessible to diverse viewers involved tasks galore, such as eliciting the service of production studios to manually dub, transcribe, and add subtitles. Those operations were costly and slow, especially for globally destined content.

Read more
Cloudinary Helps Minted Manage Its Image-Generation Pipeline at Scale

Shoppers return time and again to Minted’s global online community of independent artists and designers because they know they can count on unique, statement-making products of the highest quality there. Concurrently, the visual imagery on Minted.com must do justice to the designs into which the creators have poured their hearts and souls. For Minted’s VP of Engineering David Lien, “Because we are a premium brand, we need to ensure that every single one of our product images matches the selected configuration exactly. For example, if you pick an 18x24 art print on blue canvas, we will show that exact combination on the hero images in the PDF.”

Read more
Highlights on ImageCon 2021 and a Preview of ImageCon 2022

New year, same trend! Visual media will continue to play a monumental role in driving online conversions. To keep up with visual-experience trends and best practices, Cloudinary holds an annual conference called ImageCon, a one-of-a-kind event that helps attendees create the most engaging visual experiences possible.

Read more