Skip to content

How can I synchronously retrieve a fallback image from Glide? #5118

Open
@christinabannon

Description

@christinabannon

Glide Version: 4.15.1

Integration libraries:
No

Device/Android Version:
Android Tiramisu

Issue details / Repro steps / Use case background:
What I want to do is be able to log disk cache misses and then on those misses start a task for a URL img request.

Roughly:
Glide check memory then disk:
if in cache: return img synchronously (or very quickly if on disk cache)
else: return fallback image synchronously (or very quickly if on disk cache)
log cache miss
start task to load img from resource into cache

The code is something like this:

public static ListenableFuture<Bitmap> getBitmapFromCache(
      GlideFuturesWrapper glideFuturesWrapper, RequestManager requestManager, String url) {

    return glideFuturesWrapper.submit(
        requestManager
            .asBitmap()
            .apply(new RequestOptions().onlyRetrieveFromCache(true))
            .load(url));
  }

 public static Icon getIcon(Context context) {
    Icon icon;
    GlideFuturesWrapper glideFuturesWrapper = new GlideFuturesWrapper();
    RequestManager requestManager = Glide.with(context);

    ListenableFuture<Bitmap> futureBitmap =
        getBitmapFromCache(glideFuturesWrapper, requestManager, url);
    try {
      Bitmap bitmap = futureBitmap.get();
      icon = bitmapToIcon(bitmap);
    } catch (Exception e) {
      Log miss
      icon = getFallbackIcon();
      loadBitmapFromFifeUri(glideFuturesWrapper, requestManager, url);
    }
    return icon;
  }

The issue I am running into is that future.get() throws an exception every time there is a cache miss. I am aware that this is the intended functionality.

It would take a major refactoring effort to change the Icons passed around in this program to ImageViews, so I want for Glide to return a Bitmap as opposed to loading into an ImageView. It seems pointless to load into an ImageView that I immediately pull a Bitmap out of, and my fear is that I would get the fallback in a case where the img is on disk cache.

I currently have it in a try... catch block to deal with getting a fallback. This makes me question if there is some Glide method I may have overlooked. Does Glide have a way to synchronously serve a fallback image on an error?

Stack trace / LogCat:

GlideException: Failed to load Resource

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions