How to I get the cached Bitmap I downloaded using Volley ImageLoader? - android

Problem: I've a X amount of ImageViews that I'm adding dynamically like this:
for (int i=2; i < result.size(); i++) {
// instantiate image view
ImageView mImageView = new ImageView(this);
mImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
mImageView.setBackgroundResource(R.drawable.selectable_background_theme);
mImageView.setOnClickListener(this);
// download image and display it
mImageLoader.get(result.get(i), ImageLoader.getImageListener(mImageView, R.drawable.ic_logo, R.drawable.ic_action_refresh));
// add images to container view
mLlDescContent.addView(mImageView);
}
What want to be able to click on the image and display it in another activity in full screen. I have read about a couple of ways such as passing the Uri or passing the actual Bitmap as a byte array.
Question: How do I get the Uri or the actual Bitmap I downloaded with Volley ImageLoader. The LruCache I'm using an BitmapLruCache I found here: Android Volley ImageLoader - BitmapLruCache parameter? . Can someone help me with this or any idea to accomplish my goal.
I tried this after the above code and nothing:
Bitmap mBitmap = VolleyInstance.getBitmapLruCache().getBitmap(result.get(2));
mIvAuthorImg.setImageBitmap(mBitmap);
Edit: If i re-request the image with:
mImageLoader.get(result.get(i), ImageLoader.getImageListener(mImageView, R.drawable.ic_logo, R.drawable.ic_action_refresh));
the image is loaded from the cache, BUT if I try to access the image straight from the cache with:
Bitmap mBitmap = VolleyInstance.getBitmapLruCache().getBitmap(result.get(2));
mIvAuthorImg.setImageBitmap(mBitmap);
the image don't load. I want to be able to manipulate the image, such as size an stuff before a pass it to the next activity.

Volley depends on your implementation of a cache for successful efficient caching.
The constructor for the ImageLoader takes in an ImageCache which is a simple interface in Volley to save and load bitmaps.
public ImageLoader(RequestQueue queue, ImageCache imageCache)
A quote from the Javadoc of ImageCache interface:
Simple cache adapter interface. If provided to the ImageLoader, it will be used as an L1 cache before dispatch to Volley. Implementations must not block. Implementation with an LruCache is recommended.
Darwind is right. If you request an image and it is present in the cache it will be loaded from the cache and not from the web. This should be the case for you since you're loading and presenting an image, which if clicked should be displayed from the cache in your new activity.
You say it's not working, perhaps your implementation isn't optimized for your use case. What kind of cache are you using? Do you have one centralized RequestQueue and ImageLoader as is recommended by the Volley team?
Take a look at this question, which isn't exactly the same as yours, yet could be helpful to you. It has a simple LRU cache implementation.
Hope that helps!
Edit:
The point of Volley is not to worry about implementation details. You want an image? it will load it for you the best and fastest way possible (from memory and if it's not there via network). That's exactly the way you should look at it. Retrieving the cache and then looking in it is not the right approach IMO.
Now, if you want to manipulate the bitmap, you have a few options, the best IMO being to implement your own Image Listener pass it to the get() method instead of the default one.
Something like this:
public class MyImageListener implements ImageListener() {
#Override
public void onErrorResponse(VolleyError error) {
// handle errors
}
#Override
public void onResponse(ImageContainer response, boolean isImmediate) {
Bitmap bitmap = response.getBitmap();
if (bitmap != null) {
//
// manipulations
//
// assuming mView is a reference to your ImageView
mView.setImageBitmap(bitmap);
} else {
// display placeholder or whatever you want
}
}
}
from the Javadoc:
The call flow is this:
Upon being attached to a request, onResponse(response, true) will be invoked to reflect any cached data that was already available. If
the data was available, response.getBitmap() will be non-null.
After a network response returns, only one of the following cases will happen:
onResponse(response, false) will be called if the image was loaded.
or
onErrorResponse will be called if there was an error loading the image.

There's a bug (I'm 70% sure it's a bug) in volley currently where if a cache-expiry isn't specified (say, if you're getting an image from an S3 bucket where you have a never-expires setting), you'll always redownload from the network.
You could get around this by checking out HttpHeaderParser, and changing the relevant bits (this isn't totally crazy, as you have to include the volley source code anyway) to:
// Cache-Control takes precedence over an Expires header, even if both exist and Expires
// is more restrictive.
if (hasCacheControl) {
softExpire = now + maxAge * 1000;
} else if (serverDate > 0 && serverExpires >= serverDate) {
// Default semantic for Expire header in HTTP specification is softExpire.
softExpire = now + (serverExpires - serverDate);
} else if (serverExpires == 0) {
softExpire = Long.MAX_VALUE;
}
Then you could just pass the Uri to the activity opening the thing as a parameter. This solution has the enviable property that if something goes wrong and something happens to the image between launching the activity and displaying the bitmap, you'll still redownload it and things will work appropriately. That'll probably never/seldom happen, but it's nice to know correctness is preserved.

Related

Unable to cache images using Picasso

i am using Picasso as image loading library in my android project.
I am using it in one fragment.At first it take some time to load profile image but when i open some other fragment and then come back to the same fragment.It again takes the same amount of time to load the same image.I think it is not caching image in the memory.
Below is my java code:
Picasso.with(getContext()).load(str).fetch(new Callback() {
#Override
public void onSuccess() {
Picasso.with(getContext()).load(str).placeholder(R.drawable.user).fit().into(cv);
}
#Override
public void onError() {
TastyToast.makeText(getActivity(),"Unable to load profile image.", TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
}
});
You have use it like this
Picasso.with(getContext()).load(str).networkPolicy(NetworkPolicy.OFFLINE).fetch(new Callback() {
#Override
public void onSuccess() {
//Picasso.with(getContext()).load(str).placeholder(R.drawable.user).fit().into(cv); don't need to use it here
}
#Override
public void onError() {
TastyToast.makeText(getActivity(),"Unable to load profile image.", TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
}
});
try to take off the callback in order to know if the image is loaded, instead use the code below that automatically change the image in case of error
Picasso.with(getAplicationContext()).load("image to load").placeholder("image to show while loading").error("image in case of error").into(view);
Note the context of the first parameter: Picasso's cache still alive only if the context still alive, so if you put the ApplicationContext in the first parameter, the context and the cache keap alive even if the activity is changing. otherwise if you put getActivityContext() in the first parameter, the cache keap alive untill the activity hes been destroy
if your app is using internet connection to load image then every time you come back or go to your image containing fragment it will download image from internet so better you should store images in your app database and try to use thumbnails instead of actual images if possible it will take less time to get load

How to cancel Picasso fetch requests by tag?

When I enter an activity I'm calling this method:
private void cacheImagesAndLoadToMemory() {
for (City city : cities) {
Picasso.with(this).load(city.getImageUrl()).tag("fetch_images").fetch();
}
}
This fetches around 200 images which equates to around 45MB of data. Then I attach a fragment to this activity but when I leave the fragment I want the requests for the 200 images to be cancelled. So I have this code set up.
#Override
public void onDestroy() {
super.onDestroy();
Picasso.with(getActivity()).cancelTag("fetch_images");
}
But the fetch requests are not being cancelled. I have a bandwidth monitor on my status bar and can see that data keeps being pulled until all 200 images have been cached. Not sure what I'm doing wrong.
Seems to be a well known bug, cf. Github bug #1205.
Unfortunately Picasso project does not seem to move forward lately.

Cancelling the Image Request Android on the basis of progress - Image loader Volley , Picasso

There are many popular Image loader available in Github for image loading and caching and Managing Image Request.
Universal Image Loader
Volley
Picasso
Fresco (added enhancement )
I came across the requirement if the Imageview if no longer attached to window the request (batch and flight ) will be cancelled .
However the scrolling widget like Listview and Gridview the Imageview is frequently attached and detached from window and so the request in queue are canceled respectively .
My concern is that their no mechanism to trace the progress of image request in all above library .If Imageview is detached the request should be cancelled on the basis of progress , if the byte stream a had already done 75% of work then it should not be cancelled , which in turn will reduce the network bandwidth and decrease network call , as usually user always scroll a lot in Scrolling Widget like Listview and Gridview etc ..
Here is my understanding with Volley :
public boolean removeContainerAndCancelIfNecessary(ImageContainer container) {
/* logic to check progress of Request */
mContainers.remove(container);
if (mContainers.size() == 0) {
mRequest.cancel();
return true;
}
return false;
}
Here is my understanding with Picasso :
private void cancelExistingRequest(Object target) {
checkMain();
Action action = targetToAction.remove(target);
if (action != null) {
action.cancel();
dispatcher.dispatchCancel(action);
}
if (target instanceof ImageView) {
ImageView targetImageView = (ImageView) target;
DeferredRequestCreator deferredRequestCreator = targetToDeferredRequestCreator.remove(targetImageView);
if (deferredRequestCreator != null) {
deferredRequestCreator.cancel();
}
}
}
Here is my understanding with Universal Image Loader :
I did not figure Universal image loader permits cancelling the inline request .
void cancelDisplayTaskFor(ImageAware imageAware) {
cacheKeysForImageAwares.remove(imageAware.getId());
}
Please let me know the possibility to solve it for Network Request only . In case the image is already cached then we will cancel the request .
Battery performance is really important in Android
I can't say about Volley and Picasso but I can say how UIL works.
UIL constantly checks ImageView during task processing. If task becomes non-actual (ImageView is recycled (reused) or it's collected by GC) then UIL stops task for this ImageView.
What about if task becomes non-actual while downloading image? UIL aborts downloading if there was downloaded less than 75% of image data. If more than 75% - then UIL completes downloading (i.e. UIL caches image file in disk cache) and then cancels task.

Android gms ImageManager never loads image

I'm attempting to draw an icon for an achievement using Google Play Game Services API.
However, it is silently failing.
Approach/Issue:
The URI for the image is retrieved successfully, exists and is valid.
I use ImageManager.loadImage to get the image, with an OnImageLoadedListener for callback (com.google.android.gms.common.images.ImageManager).
However OnImageLoadedListener's method, onImageLoaded, is never called.
No error's, no evidence, just completely ignored, I even waited 10 minutes just in case.
Code:
// Get URI [is valid, exists, is of type png, I checked]
Uri uri = getAchievementIconUri(id);
// Use ImageManager to get the icon image
ImageManager.create(context).
loadImage(new ImageManager.OnImageLoadedListener() {
#Override
public void onImageLoaded(Uri u, Drawable d, boolean r) {
/*
* This code is never reached, no call to onImageLoaded is made!
*/
}
}, uri);
It's probably a very late answer, but it might help other people experiencing the same. From the latest google documentation, https://developers.google.com/android/reference/com/google/android/gms/common/images/ImageManager.html#public-methods
Note that you should hold a reference to the listener provided until the callback is complete. For this reason, the use of anonymous implementations is discouraged.
This might explain the behaviour you experienced, as in the first code snippet provided, no reference to the Listener was retained.
Well, for what it matters, I never solved the problem entirely.
It seems that it actually displays the icons occasionally, whenever it feels like it.
I implemented a workaround that loads a compressed, cached version of the image and later replaces it with the ImageManager provided image if it can be bothered doing so.
If anybody works out the correct answer then I will remove this workaround, but until then its here for anybody with the same issue.
Code that loads the local icons:
public Bitmap loadDefaultAchievementIcon(final String id) {
// Get drawable ID for achievement
// iconIdMap is a map of achievement ID strings against their drawable res IDs
int resID = iconIdMap.containsKey(id) ? iconIdMap.get(id) :
// Fallback/unknown icon
R.drawable.ic_action_achievements;
// Load and return bitmap
InputStream is = getResources().openRawResource(resID);
Bitmap bitmap = BitmapFactory.decodeStream(is);
return bitmap;
}

Android Volley - Some disc cached images dont get displayed?

I've run into this weird error, where some images get cached as usual and some don't, any idea why?
Both images do get displayed and memory cached just fine, but when offline some display error image.
For example, this works fine:
http://cs4381.vk.me/u73742951/a_58a41ac2.jpg
However, this does not: http://upload.wikimedia.org/wikipedia/commons/thumb/d/d7/Android_robot.svg/220px-Android_robot.svg.png
Both work fine displaying and memcaching but the second doesn't get displayed from disk cache, although I think I see it being saved, as app says it has 12kB cache in the system settings
Edit
I checked out a clean copy of Volley and it does the same thing. Its definatelly a bug...
From what Ive found out its that images do get cached, but Bitmap cachedBitmap = mCache.getBitmap(cacheKey); always returns null, so the cache says it doesnt have the bitmaps and then proceedes to download it again, and fail when offline, weird
The reason you're not getting any hits is because the default behavior in Volley for disk caching is dependent on the HTTP headers of the element you're requesting (in your case, an image).
Check the volley logs and see if you get the "cache-hit-expired" message - that means that the image was cached but it's TTL is expired as far as the default disk cache is concerned.
If you want the default settings to work, the images must have a Cache-Control header like max-age=??? where the question marks indicate enough seconds from the time it was downloaded.
If you want to change the default behavior, I'm not sure, but I think you have to edit the code a bit.
Look at the CacheDispatcher class in the Volley source.
Hope that helps.
A quick and dirty way:
private static class NoExpireDiskBasedCache extends DiskBasedCache
{
public NoExpireDiskBasedCache(File rootDirectory, int maxCacheSizeInBytes)
{
super(rootDirectory, maxCacheSizeInBytes);
}
public NoExpireDiskBasedCache(File rootDirectory)
{
super(rootDirectory);
}
#Override
public synchronized void put(String key, Entry entry)
{
if (entry != null)
{
entry.etag = null;
entry.softTtl = Long.MAX_VALUE;
entry.ttl = Long.MAX_VALUE;
}
super.put(key, entry);
}
}

Categories

Resources