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

On-Demand Viewing of Live Video Presents New Opportunities

In early 2020, Cloudinary was planning its fourth annual ImageCon conference, a two-day event in the heart of San Francisco, where we’d congregate with curious digital-media minds to brainstorm best practices for media management. Instead, the COVID-19 pandemic forced the entirety of ImageCon 2020 online. As with all other events being planned, we had to overhaul the content to be communicated on video. Gratifyingly, we found the right partner—the event platform Bizzabo—to turn that into a reality.

Read more
Why the Future of E-commerce Is Live

In a previous post, I discussed how “going live” is gaining popularity across industries and verticals. What began as a way for gamers to jam together has evolved into a medium for broader entertainment and business purposes. To continue the conversation, this post unpacks the current trends of shoppable live streams to shine a light on how brands are leveraging “lives” to connect with shoppers in new ways.

Read more
An Overview of Live-Streaming Video Trends

“Let’s go live.” For decades, that’s what newscasters say as they cut to real-time footage of a colleague reporting in the field. The live-video feed adds visual interest and perspective to a story beyond what can be communicated by someone sitting behind the news desk. In the same way, live-streaming video nowadays adds context to other consumer environments. From gaming and events to shopping and social media, “going live” enhances everyday experiences, and it’s something anyone can do with relative ease.

Read more
Readying Live Streams for Video on Demand

When planning a live broadcast or stream, companies often overlook the redistribution phase, but live-stream videos are useful well beyond their initial streaming. Why? Because not everyone watches the first run. For a wider audience, it makes sense to repost live content on your website under an “events” tab, on YouTube, and other social sites for video on demand (VOD). However, preparing footage for reposting can be a lot of work.

Read more