onBitmapLoaded never called - android

I've got an issue with onBitmapLoaded. The method is not called when it should be (it is called the second time i enter my view). Nevertheless i keep a reference to my target since i add it to an arraylist.
I don't understand why it's not working.
Does someone have an idea ?
public void loadBitmap() {
if(loadtarget == null) {
loadtarget = new Target(){
#Override
public void onPrepareLoad(Drawable arg0) {
Log.d("Bitmap","On prepare load");
targetList.remove(this);
return;
}
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
Log.d("Bitmap","OKAY for :" + filename);
targetList.remove(this);
handleLoadedBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
Log.d("Bitmap","Error for :" + filename);
}
};
}
targetList.add(loadtarget);
Picasso.with(context).load(imageUrl).into(loadtarget);
}

If targetList and loadtarget are both local variables then they will be marked for GC collecting as soon as the method finishes.
Make sure targetList is a class variable so that its outlives the method.

I've find some kind of trick to solve my problem.
By replacing :
Picasso.with(context).load(imageUrl).into(targetList.get(i));
With :
Picasso.with(context).load(imageUrl).transform(new Transformation() {
#Override
public Bitmap transform(Bitmap source) {
handleLoadedBitmap(source);
return source;
}
#Override
public String key() {
return "";
}
}).into(imageView); // imageView is a fictive imageView allocated only for this operation
my code is working. I'm not sure that it's the best solution but it fixed my problem.

Related

Picasso Target has been garbage collected

Good day.I have an google map with cluster manager.Simple one,where i use the cluster to draw markers grouped or not.Anyway i got an method callback from cluster manager which is the Cluster item render one.Inside that callback i am applying custom image to the marker:The user image inside marker.I found Picasso to be the best to handle bitmap loading and at the same time got me lots of headache.I am using Target class from Picasso to initiate the bitmap callbacks:OnPreLoad,OnFail,OnBitmapLoaded.The issue is that on first cluster item render the onBitmapLoaded not called and generally it is never gets called unless it has been touched second time.On first time nothing happens,no callback is triggered except OnPreLoad and by googling i found that the great Picasso holds weak reference to the class.I tried all the examples of the google:Making Target reference strong(getting the initialazation of class out of method and init the class inside my class like the follows)
#Override
protected void onClusterItemRendered(MarkerItem clusterItem, Marker marker) {
mMarker = marker;
mMarkerItem = clusterItem;
Picasso.with(mContext).load(clusterItem.getImageUrl()).transform(new CircleTransformation()).into(target);
}
private Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
Log.d(TAG, "onBitmapLoaded: ");
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
Log.d(TAG, "onBitmapFailed: ");
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
Log.d(TAG, "onPrepareLoad: ");
}
};
#Override
protected void onBeforeClusterItemRendered(MarkerItem item, MarkerOptions markerOptions) {
markerOptions.title(item.getTitle());
markerOptions.icon(item.getIcon());
}
At this point i get the same result....Sometimes the bitmap loaded and sometimes not.Mostly not...
Anyway i have tried to implement the interface class to my own class as follows:
public class PicassoMarkerView implements com.squareup.picasso.Target {
private static final String TAG = "MarkerRender";
private Bitmap mMarkerBitmap;
private ClusterManager<MarkerItem> mClusterManager;
private MarkerItem mMarkerItem;
private Marker mMarker;
public PicassoMarkerView() {
}
#Override
public int hashCode() {
return mMarker.hashCode();
}
#Override
public boolean equals(Object o) {
if (o instanceof PicassoMarkerView) {
Marker marker = ((PicassoMarkerView) o).mMarker;
return mMarker.equals(marker);
} else {
return false;
}
}
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap,
mMarkerBitmap.getWidth() - 15, (int) (mMarkerBitmap.getHeight() / 1.5 - 15),
false);
mMarker.setIcon(BitmapDescriptorFactory.fromBitmap(overlay(mMarkerBitmap, scaledBitmap, 8, 7)));
Log.d(TAG, "onBitmapLoaded: ");
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
Log.d(TAG, "onBitmapFailed: ");
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
Log.d(TAG, "onPrepareLoad: ");
}
private Bitmap overlay(Bitmap bitmap1, Bitmap bitmap2, int left, int top) {
Bitmap res = Bitmap.createBitmap(bitmap1.getWidth(), bitmap1.getHeight(),
bitmap1.getConfig());
Canvas canvas = new Canvas(res);
canvas.drawBitmap(bitmap1, new Matrix(), null);
canvas.drawBitmap(bitmap2, left, top, null);
return res;
}
public void setMarkerBitmap(Bitmap markerBitmap) {
this.mMarkerBitmap = markerBitmap;
}
public void setClusterManager(ClusterManager<MarkerItem> clusterManager) {
this.mClusterManager = clusterManager;
}
public void setMarkerItem(MarkerItem markerItem) {
this.mMarkerItem = markerItem;
}
public void setMarker(Marker marker) {
this.mMarker = marker;
}
}
Unfortunatally this is not working either...Same result...So please dear friends can you give me an working example of this?As far as i could google,the issue mostly happens to the user which try to do this inside loop and my onClusterItemRender some sort of loop lets say as it is triggered every time marker is visible to user,so yeah it is triggered several times and as fast as loop so give me some idea please and help me out...
Important to mention that i do not need to use methods from picasso like fetch(),get() as they are not necessary and not fitting the purpose of the app.
I encountered similar issue and holding reference to the target didn't help at all.
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.
Beside Picasso I used Glide, and I was amazed by the results, Glide's api worked flawlessly in every aspect 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 ^^ ).
So my suggestion to you is:
Use glide over Picasso (no such weak reference on their target).
Since I had to use both libraries I ended up using get() in an handler, not sure if it will help you but it solved my problem:
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);
}
}
}
});

IntentService Terminated before Picasso loads Bitmap

I'm trying to use an IntentService for processing and uploading images that's running in a different process to have more memory. I'm Using also Picasso to load the Image. When the Image is small the bitmap is loaded successfully and uploaded, however if the image is big the IntentService is terminated before Picasso is done loading It.
Picasso have to run on UIThread
Here is the code.
private void downloadImage(File file) {
final Uri uri = Uri.fromFile(file);
Handler uiHandler = new Handler(Looper.getMainLooper());
uiHandler.post(new Runnable() {
#Override
public void run() {
Picasso.with(NewImageProcessingService.this).load(uri).transform(new ImageLoadingUtil.DecreaseQualityTransformation(imageQuality)).into(NewImageProcessingService.this);
}
});
}
#Override
protected void onHandleIntent(Intent intent) {
File file = (File) intent.getSerializableExtra(KEY_IMAGE_FILE);
imageQuality = ImagesUtils.IMAGE_QUALITY
.values()[intent.getIntExtra(IMAGE_QUALITY, ImagesUtils.IMAGE_QUALITY.DEFAULT.ordinal())];
downloadImage(file);
}
This question is quite old, but if anyone steps by. The Target is getting garbage collected before it can show the bitmap.
Use it like this
public class BitmapLoader {
public static Target getViewTarget(final OnImageLoadingCompleted onCompleted) {
return new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
onCompleted.imageLoadingCompleted(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
}
}
You need to have a strong reference to the Target so have a field in your IntentService holding it e.g.
private Target viewTarget;
viewTarget = BitmapLoader.getViewTarget(bitmap -> {
// do stuff with the bitmap
});
new Handler(Looper.getMainLooper()).post(() -> Picasso.with(getApplicationContext()).load(object.getImageUrl()).into(viewTarget));

Fade in animation while loading image Using Picasso

I want to show a fade effect when image is loading on Imageview. I am using picasso to cache image and display in image view. I have searched alot for this but couldnt find any solution.
I have used earlier before and i know in some version they had .fade(int Duration) method to fade image while loading but i couldnt find this method anymore.
Here is what i am doing now
Picasso.with(context)
.load(viewHolder.data.imageList.get(0).url)
.networkPolicy(NetworkPolicy.OFFLINE)
.placeholder(R.drawable.a_place_holder_list_view)
.error(R.drawable.a_place_holder_list_view)
.into(viewHolder.ivUser, context.loadImage(viewHolder.ivUser, viewHolder.data.imageList.get(0).url));
public Callback loadImage(RoundedImageView ivUser, String url) {
return new callback(ivUser, url);
}
public class callback implements Callback {
RoundedImageView imageView;
String url;
public callback(RoundedImageView imageView, String url) {
this.imageView = imageView;
this.url = url;
}
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(BaseActivity.this)
.load(url)
.placeholder(R.drawable.a_place_holder_list_view)
.error(R.drawable.a_place_holder_list_view)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Log.v("Picasso", "Could not fetch image");
}
});
}
}
Please help me i have been stuck in this for quite long time.
Thanks in advance.
Quoting Jake Wharton's answer here:
If the image comes from anywhere except the memory cache the fade
should be automatically applied.
If you check the PicassoDrawable class
boolean fade = loadedFrom != MEMORY && !noFade;
if (fade) {
this.placeholder = placeholder;
animating = true;
startTimeMillis = SystemClock.uptimeMillis();
}
.
.
.
#Override public void draw(Canvas canvas) {
if (!animating) {
super.draw(canvas);
} else {
.
.
.
fade effect is already applied for images loaded from n/w and not memory/cache
and FADE_DURATION = 200f; //ms
To force fade, again quoting jake wharton's answer here:
You can specify noFade() and then always play an animation in the
image loaded callback. You can also rely on the callback being called
synchronously to determine if an animation needs played.
final AtomicBoolean playAnimation = new AtomicBoolean(true);
Picasso.with(context).load(..).into(imageView, new Callback() {
#Override public void onLoad() {
if (playAnimation.get()) {
//play fade
Animation fadeOut = new AlphaAnimation(0, 1);
fadeOut.setInterpolator(new AccelerateInterpolator());
fadeOut.setDuration(1000);
imageView.startAnimation(fadeOut);
Animation fadeOutPlaceholder = new AlphaAnimation(1, 0);
fadeOutPlaceholder.setInterpolator(new AccelerateInterpolator());
fadeOutPlaceholder.setDuration(1000);
placeHolderImageView.startAnimation(fadeOutPlaceholder);
}
}
//..
});
playAnimation.set(false);
You can simply do
Picasso.with(context).load(url).fetch(new Callback(){
#Override
public void onSuccess() {
imageView.setAlpha(0f);
Picasso.with(context).load(url).into(imageView);
imageView.animate().setDuration(300).alpha(1f).start();
}
#Override
public void onError() {
}
});
I do this:
Picasso.get().load(url).fit().noFade().centerInside().into(imageView, new Callback() {
#Override
public void onSuccess() {
imageView.setAlpha(0f);
imageView.animate().setDuration(200).alpha(1f).start();
}
#Override
public void onError(Exception e) {
}
});

Clear Cache memory of Picasso

I'm trying to clear the cache memory of Picasso via Android coding.
Can anyone please help me in this issue..?
I have tried using the following code, but this was not useful in my case:
Picasso.with(getActivity()).load(data.get(pos).getFeed_thumb_image()).skipMemoryCache().into(image);
Use this instead :
Picasso.with(getContext()).load(data.get(pos).getFeed_thumb_image()).memoryPolicy(MemoryPolicy.NO_CACHE).into(image);
Remove cache of Picasso like this.
public class Clear {
public static void clearCache (Picasso p) {
p.cache.clear();
}
}
This util class can clear the cache for you. You just have to call it:
Clear.clearCache(Picasso.with(context));
EDIT:
The class Clear must be in the package :
package com.squareup.picasso;
Because cache is not accessible from outside that package.
Like in this answer: https://stackoverflow.com/a/23544650/4585226
if you are trying to load an image through Json(from db) try clearing the networkCache for a better result.
Picasso.with(context).load(uri).networkPolicy(NetworkPolicy.NO_CACHE)
.memoryPolicy(MemoryPolicy.NO_CACHE)
.placeholder(R.drawable.bv_logo_default).stableKey(id)
.into(viewImage_imageView);
Instead of clearing the complete cache if one wants to refresh the image with the given Uri. try this Picasso.with(context).invalidate(uri); it internally removes the key from the cache maintained by Picasso.
Excerpt from Picasso.java
/**
* Invalidate all memory cached images for the specified {#code uri}.
*
* #see #invalidate(String)
* #see #invalidate(File)
*/
public void invalidate(Uri uri) {
if (uri == null) {
throw new IllegalArgumentException("uri == null");
}
cache.clearKeyUri(uri.toString());
}
When activity destroy, unfortunately bitmap was not recycled if we're using Picasso. I try to programmatically recycle bitmap, what's loaded in to image view. There is a way to reference to loaded bitmap by using Target.
Target mBackgroundTarget = new Target() {
Bitmap mBitmap;
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
if (bitmap == null || bitmap.isRecycled())
return;
mBitmap = bitmap;
mBgImage.setImageBitmap(bitmap);
mHandler.post(new Runnable() {
#Override
public void run() {
// Do some animation
}
});
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
recycle();
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
/**
* Recycle bitmap to free memory
*/
private void recycle() {
if (mBitmap != null && !mBitmap.isRecycled()) {
mBitmap.recycle();
mBitmap = null;
System.gc();
}
}
};
And when Activity destroy, I call onBitmapFailed(null) to recycle loaded bitmap.
#Override
protected void onDestroy() {
super.onDestroy();
try {
if (mBackgroundTarget != null) {
mBackgroundTarget.onBitmapFailed(null);
Picasso.with(context).cancelRequest(mBackgroundTarget);
}
} catch (Exception e) {
e.printStackTrace();
}
}
But remember, DON'T CACHE IMAGE IN MEMORY by this case, It will cause Use recycled bitmap exception.
Picasso.with(context)
.load(imageUrl)
.resize(width, height)
.memoryPolicy(MemoryPolicy.NO_CACHE)
.into(mBackgroundTarget);
Hope this help.
If you keep reference of your custom Downloader implementation you can clear cache.
public class PicassoUtil {
private static Picasso sInstance;
private static OkHttp22Downloader sDownloader;
public static Picasso getPicasso(Context context){
if(sInstance == null) {
sDownloader = new OkHttp22Downloader(context)
Picasso.Builder builder = new Picasso.Builder(context);
builder.downloader(sDownloader);
sInstance = builder.build(sDownloader);
}
return sInstance;
}
public static void clearCache(){
if(sDownloader != null){
sDownloader.clearCache();
}
}
}
It is important to have access to your http client and its Cache. In my implementation there is access to the cache, hence clearing cache with clearCache() method.
i had the same problem.
It worked for me.
I used Picasso in RecycleView inside a dialog. When i closed dialog, picasso doesnt clear cache. But while you are using the dialog it clears image cache. However there is some cache that is not cleared. Maybe the cache that was not cleared is the last you seen in dialog before dialog.dismiss().
use this
memoryPolicy(MemoryPolicy.NO_CACHE,MemoryPolicy.NO_STORE)
Picasso.with(activity).load(file).resize(100,100).centerCrop().memoryPolicy(MemoryPolicy.NO_CACHE,MemoryPolicy.NO_STORE).into(contactImage, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
}
});
Picasso.with(this.getContext()).load(gamePlayer.getPlayerProfileUrl()).skipMemoryCache().into(iv);
This also works

How to load JPEG as a BITMAP from server using Picasso

I've tried using the method:
bmp = (Bitmap) Picasso.with(Feed.this).load(IMAGE_URL+loadImageUrl).resize(width, width).get();
But I get a "Picasso DownloadResponseException" even when I take out the (Bitmap) typeCast
I've also tried:
Picasso.with(Feed.this).load(IMAGE_URL+image).resize(width, width).into(target);
With
private Target target = new Target() {
#Override
public void onBitmapFailed(Drawable arg0) {
// TODO Auto-generated method stub
Log.d("FAILED", "Bitmap Failed");
}
#Override
public void onPrepareLoad(Drawable arg0) {
// TODO Auto-generated method stub
}
#Override
public void onBitmapLoaded(Bitmap bmp, LoadedFrom arg1) {
RoundedCornersDrawable drawable = new RoundedCornersDrawable(getResources(), bmp);
theImage.setImageDrawable(drawable);
}
};
But it gives me nothing, the image doesn't load it just stays blank and the log message under the BitmapFailed method does not come up... The images stored on my server are of type "jpg".
Please help me
Figured it out. Turns out I had the wrong URL. Also make sure you Don't call that Picasso.get() method inside the UI thread...

Categories

Resources