Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

picasso - onBitmapLoaded of Target object not called on first load

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--

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...