onBitmapLoaded of Target object not called on first load

psv picture psv · Jun 12, 2014 · Viewed 42.4k times · Source

In my function :

public void getPointMarkerFromUrl(final String url, final OnBitmapDescriptorRetrievedListener listener) {
final int maxSize = context.getResources().getDimensionPixelSize(R.dimen.icon_max_size);
Target t = new Target() {
  @Override
  public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
    if (bitmap != null)
      listener.bitmapRetrieved(getBitmapDescriptorInCache(url, bitmap));
    else
      loadDefaultMarker(listener);
  }

  @Override
  public void onBitmapFailed(Drawable errorDrawable) {
    loadDefaultMarker(listener);
  }

  @Override
  public void onPrepareLoad(Drawable placeHolderDrawable) {
  }
};

Picasso.with(context)
    .load(url)
    .resize(maxSize, maxSize)
    .into(t);
}

The onBitmapLoaded() is never called the first time I load pictures. I've read some topic like https://github.com/square/picasso/issues/39 which recommand to use fetch(Target t) method (it seems to be a problem of weak reference...), but this function is not available in the last release of picasso (2.3.2). I've only a fetch() method, but I cannot use into(mytarget) at the same time

Could you explain me how to use fetch() with a custom Target please ? Thank you.

Doc : http://square.github.io/picasso/javadoc/com/squareup/picasso/RequestCreator.html#fetch--

Answer

wrb picture wrb · Nov 13, 2014

As noted by the other respondents (@lukas and @mradzinski), Picasso only keeps a weak reference to the Target object. While you can store a strong reference Target in one of your classes, this can still be problematic if the Target references a View in any manner, since you'll effectively also be keeping a strong reference to that View as well (which is one of the things that Picasso explicitly helps you avoid).

If you are in this situation, I'd recommend tagging the Target to the View:

final ImageView imageView = ... // The view Picasso is loading an image into
final Target target = new Target{...};
imageView.setTag(target);

This approach has the benefit of letting Picasso handle everything for you. It will manage the WeakReference objects for each of your views - as soon as one is no longer needed, whatever Target processing the image will also be released, so you're not stuck with memory leaks due to long-lived targets, but your Target will last as long as its view is alive.