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

Partner news: Cloudinary-Getty Images Integration

Supported by intelligent automation, Cloudinary serves as an effective conduit between media asset management and delivery so you can take maximum advantage of assets, compress workflows, and build and coordinate engaging and inspiring customer experiences. Through Cloudinary’s Digital Asset Management (DAM) solution, which employs the company’s innovative image and video APIs, creative and marketing teams can benefit from them, as well as from many AI-powered and automated capabilities. As a result, you can transform, optimize, and deliver media at scale on an intuitive UI.

Read more
Why Audio in Video Matters

Many content creators and consumers tend to regard video as visuals, but that’s only part of the experience. Immersive video content includes strong audio. Just like in a movie, the audio for video content comprises many components: the narrator or subjects, the background music that sets the mood and draws viewers in, sound effects, and so forth.

Read more

For Developers: the HTML <picture> Element Explained

By Amarachi Amaechi
For Developers: the HTML <picture> Element Explained

We all know the good ol', tireless <img> element, which has been a long-time go-to for inserting graphics into webpages. Time doesn’t stop, however, and neither do technological advancements. So, let’s get you up to speed with the element’s modern alternative: the <picture> element.

Read more