onBitmapLoaded of Target object not called on first load

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

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

回答1:

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.



回答2:

Picasso does not hold a strong reference to the Target object, thus it's being garbage collected and onBitmapLoaded is not called.

The solution is quiet simple, juste make a strong reference to the Target.

public class MyClass {    private Target mTarget = new Target() {...};     public void getPointMarkerFromUrl(final String url, final OnBitmapDescriptorRetrievedListener listener) {           Picasso.with(context)          .load(url)          .resize(maxSize, maxSize)          .into(mTarget);    } }       


回答3:

If I had ImageView I would simple make like this: imageView.setTag(target);

I use next solution for loading Bitmaps into notifications, so I need only bitmap.

So create Set witch will store Target objects and remove them on finish loading.

final Set protectedFromGarbageCollectorTargets = new HashSet();  private void loadBitmap(String url) {    Target bitmapTarget = new BitmapTarget(nEvent);    protectedFromGarbageCollectorTargets.add(bitmapTarget);    Picasso.with(context).load(url).into(bitmapTarget); }  class BitmapTarget implements Target {          @Override         public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom loadedFrom) {                      //handle bitmap                     protectedFromGarbageCollectorTargets.remove(this);                 }             }         }          @Override         public void onBitmapFailed(Drawable drawable) {             protectedFromGarbageCollectorTargets.remove(this);         }          @Override         public void onPrepareLoad(Drawable drawable) {          }     } 


回答4:

ImageView profile = new ImageView(context);         Picasso.with(context).load(URL).into(profile, new Callback() {             @Override             public void onSuccess() {                 new Handler().postDelayed(new Runnable() {                     @Override                     public void run() {//You will get your bitmap here                          Bitmap innerBitmap = ((BitmapDrawable) profile.getDrawable()).getBitmap();                     }                 }, 100);             }              @Override             public void onError() {              }         }); 


回答5:

Like @lukas said (and quoting), Picasso does not hold a strong reference to the Target object. To avoid garbage collection you must hold a strong reference to the object.

About fetch() method. It's pretty clear in the documentation that fetch() is not to be used with an ImageView nor a Target, it's just to "warm" up the cache and nothing else, so you're not going to be able to use it the way you want.

I recommend you holding a strong reference like @lukas explained, it should work. If not please open up a new issue on the GitHub page of the project.



回答6:

I encountered similar issue and holding reference to the target didn't helped at all so I used the following code which returns a Bitmap:


Bitmap bitmap = picasso.with(appContext).load(url).get(); 

on the down side -> there's no callback and you can't call this function on the main thread, you have to run this function on a background thread as in the following example:


handlerThread = new HandlerThread(HANDLER_THREAD_NAME); handlerThread.start();  Handler handler = new Handler(handlerThread.getLooper()); handler.post(new Runnable() {     @Override     public void run() {         Bitmap bitmap = null;         try {             bitmap = picasso.with(appContext).load(url).get();         } catch (IOException e) {             e.printStackTrace();         }finally {             if (bitmap != null) {                 //do whatever you wanna do with the picture.                 //for me it was using my own cache                 imageCaching.cacheImage(imageId, bitmap);             }         }     } }); 

Another thing that works a whole lot better is just using Glide!

I needed to use both of them since the purpose of my project was to use 2 different image downloading api's to show an images gallery and to give the user the ability to choose which api to use.

I have to say, I was amazed by the results, Glide's api worked flawlessly in every aspect (Glide's target doesn't have weak reference) wile Picasso gave me hell (that was my first time using Glide, I usually used Picasso so far, seems like today it's gonna change ^^ ).



回答7:

Here is the solution for those who aren't using a view. This helper method uses a list to temporarily store the target object until a result is returned so that it isn't gc'd:

private List targets = new ArrayList();  public void downloadBitmap(final Context context, final String url, final MyCallback callback) {     Target target = new Target() {          @Override         public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {             targets.clear();             callback.onSuccess(bitmap);         }          @Override         public void onBitmapFailed(Drawable errorDrawable) {             targets.clear();             callback.onFailure(null);         }          @Override         public void onPrepareLoad(Drawable placeHolderDrawable) {         }     };     targets.add(target);     Picasso.with(context).load(url).into(target); } 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!