Glide not loading image or throwing error in AsyncTask - android

Glide is not loading my image synchronously inside my AsyncTask.
#Override
protected Boolean doInBackground(EventAppSetupModel... params) {
File icon = Glide.with(mContext).load("https://www.google.nl/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png").downloadOnly(512, 512).get();
The AsyncTask just hangs. I am not getting any logging, even with the error logging enabled. When i set a listener, none of the methods of the listeners are ever called. If i do set a timeout of 15 seconds, it times out without giving me any other information. This happens for any image for any server.
How can I load and resize an image into a file with Glide synchronously?

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.

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

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.

Android Webview's ClearCache is very slow

I am using WebViews in an Android app, and I need to prevent the WebViews from caching.
Unfortunately it seems like this seemingly simple goal is nearly impossible to achieve. The solution I have resorted to use is to execute webview.clearCache(true) in the onPageFinished event so that the cache is cleared each time a page is loaded. There are some issues...
I have noticed that as the cache grows it becomes very time consuming for the clearCache method to execute. Sometimes if you execute clearCache and then switch to a different Activity that contains different webview, that webview will not load for a few seconds because it is still waiting on the previous clearCache operation to finish.
What's worse is that execution time of subsequent calls to clearCache does not seem to decrease after the cache has been already cleared. If the call to clearCache takes 3 seconds to complete and then I immediately call clearCache a second time, then I would expect the second call to clearCache to complete almost immediately. But that is not what I'm experiencing; I'm experiencing that the second call to clearCache still take approximately 3 seconds.
Has anyone else experienced this? Is there any way to improve performance? Waiting 2-3 seconds for a webview to load (from the local filesystem) is horrible.
EDIT:
Here is my best alternative to actually clearing the cache. It more or less works but it's sort of flaky and I'm not 100% happy with it (written in Mono c#):
public class NoCacheWebClient : WebViewClient
{
string previous;
public override void OnPageStarted(WebView view, string url, Android.Graphics.Bitmap favicon)
{
base.OnPageStarted(view, url, favicon);
if (!string.Equals(previous, url))
{
previous = url;
view.Reload(); //re-load once to ignore cache
}
else
{
previous = null;
}
}
}
1) Try using setAppCacheEnabled and setAppCacheMaxSize to limit the cache size to very little , lower cache size will result in faster cleanup.
Ex: wv.getSettings().setAppCacheMaxSize(1);
OR
2) If you don't need the cached data then simply set setCacheMode(WebSettings.LOAD_NO_CACHE); , which means
"Don't use the cache, load from the network", even though data is cached.
In-short, simply ignore the cached data, android will take care of it.
OR
3) you can also try the below code for no-caching,
Note: this is only available for Android API 8+
Map<String, String> noCacheHeaders = new HashMap<String, String>(2);
noCacheHeaders.put("Pragma", "no-cache");
noCacheHeaders.put("Cache-Control", "no-cache");
view.loadUrl(url, noCacheHeaders);
OR
4) Clear the cache every-time whenever page load finishes.
Something like this in the WebViewClient.
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.clearCache(true);
}
OR
5) You can try deleting whole cached database at once.
context.deleteDatabase("webview.db");
context.deleteDatabase("webviewCache.db");
This might give a bit faster result, hope so.
As you are going to the next activity finish the previous activity. So that you can free all memory occupied by that activity.
Hope this helps.

Categories

Resources