I am working on an app with a lot of dynamic and changing content.
I pull all my data from my server when the app is loading.
As a result, nearly every activity/fragment is loading separately which will cause the user to wait a lot of time for each "page" to load individually.
My goal is to create one loading page when the app starts while being responssible for all the downloading and will disk cache all the images and info(strings) and ti pull them at the right time. (or at least to most of it)
I had the chance to use retrofit, okhttp and Picasso as a single additional library, I know though that they can work together and to be synced and that disk cacheing is available through at least two of this libraries (picasso and okhttp) I'm not sure though which one should do which part and how I can sync them together.
I will appreciate every Tip/Guidance, thanks ahead.
okhttp provides support for cache control headers. I've implemented them in an app before to provide a cache when network is flaky using this guide like so:
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(cacheDirectory, cacheSize);
client = new OkHttpClient.Builder()
.cache(cache)
.build();
As Retrofit uses okhttp internally (if you're using the latest at least), you don't configure any caching for it. Just use the okhttp client you just configured:
RestAdapter restAdapter = new RestAdapter.Builder()
.setClient(new OkClient(client))
.setServer("http://example.com")
...
.build();
Picasso automatically caches images using some default cache size limit. You can change Picasso's default, and I've found some answers here and here. You could set the cache size in the onCreate of your application:
Picasso.Builder builder = new Picasso.Builder(this);
builder.downloader(new OkHttpDownloader(this,Integer.MAX_VALUE));
Picasso picasso = builder.build();
picasso.setIndicatorsEnabled(true);
picasso.setLoggingEnabled(true);
Picasso.setSingletonInstance(picasso);
Picasso also lets you prefetch images earlier on in an app's lifecycle if you have the time to begin with (say, on a loading screen) and want to make later parts of the app load quicker. To do that, I would use the fetch method from the Picasso builder to get the images, but not insert them into any ImageViews. You can Google it too, but there's a quick answer here which explains the background behind this:
Picasso.with(getApplicationContext())
.load(url)
.fetch();
IIRC you need to make sure you fetch the same sized and transformed image as you try and retrieve later, because Picasso caches the transformed image result rather than the raw downloaded image.
Related
How can I ommit disc caching in per request basis as in Glide with setDiscCacheStrategy (other than downloadimg the image normally and than evic it from disc cachd)
Assuming you use ImageRequestBuilder to build ImageRequest objects, you need to call disableDiskCache() on the builder.
For example:
ImageRequest request = ImageRequestBuilder
.newBuilderWithSource(uri)
.disableDiskCache()
.build();
if its just for debug builds you can do it another way. in my case i was not using imageRequestBuilder. so i just added a random number as a query param to the url fresco is loading. it will make fresco get a new image everytime almost. no cache.
I want to prefetch images using Picasso and save them all to disk upon opening the app (no lazy loading on the fly). To make sure the cache is big enough I am using the following code in my Application onCreate
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
OkHttpClient client = new OkHttpClient.Builder()
.cache(new Cache(directory, Integer.MAX_VALUE))
.build();
OkHttp3Downloader okHttp3Downloader = new OkHttp3Downloader(client);
Picasso.Builder builder = new Picasso.Builder(this);
builder.downloader(okHttp3Downloader);
Picasso built = builder.build();
built.setIndicatorsEnabled(false);
built.setLoggingEnabled(false);
Picasso.setSingletonInstance(built);
So here I set my cache size to Integer.MAX_VALUE which should be big enough ;)
I use code similar to this line to prefetch the image: Picasso.with(context).load(url).fetch();.
Now when I kill my internet and mobile data, no images are loaded even though the my code is fetching items. Any ideas why?
Maybe the problem is loosing state. Did you try to extend Application class (like this) and keep Picasso instance here?
In similar situation when I needed to fetch lots of images, I save them to internal memory (not just in some cache) - to prevent from reloading, and save uri's to files into SQLite and then use Picasso to work with such URI's. (don't forget to check that user don't delete anything).
In the end I created my own image manager that downloads and store images (still using picasso to download them).
Here is my approach:
In Application's onCreate method do:
Picasso picasso = new Picasso.Builder(this)
.downloader(new OkHttp3Downloader(this,Integer.MAX_VALUE))
.build();
picasso.setIndicatorsEnabled(BuildConfig.DEBUG);
picasso.setLoggingEnabled(BuildConfig.DEBUG);
Picasso.setSingletonInstance(picasso);
And then wherever you want to load your images call this for each image's url:
Picasso.with(context).load(url).fetch();
From doc:
fetch()
Asynchronously fulfills the request without a ImageView or Target. This is useful when you want to warm up the cache with an image.
You can even pass in callback to check for possible errors
Hi I'm trying to understand how to use the Picasso library to cache my downloaded images, so I created a very simple app with one activity, put an ImageView on it and wrote the simplest Picasso line:
Picasso.with(this).load("http://www.estambiente.it/wp-content/uploads/2009/12/Patern_test.jpg")
.placeholder(R.drawable.holder)
.error(R.drawable.error)
.into(im);
but I wanted to see the cache indicators, so I wrote this to show them:
OkHttpClient picassoClient = new OkHttpClient();
Picasso picasso = new Picasso.Builder(this).downloader(new OkHttpDownloader(picassoClient)).build();
picasso.setIndicatorsEnabled(true);
picasso.load("http://www.estambiente.it/wp-content/uploads/2009/12/Patern_test.jpg").into(im);
this code always show the red flag (meaning the image comes from the network) and if I try to open the app while I'm not connected, the error image is shown.
what am I missing here?
I have been trying to use Fresco library by Facebook.
From the documentation I understood that the caching of images works out of the box with the ImagePipelines when we use the SimpleDraweeView. I pretty much see things working perfectly only with the minor hiccup that eventhough Fresco fetches images from my URI the images in the DiskCache and other Caches are not replaced by it.
I'm positive about my code fetching the images because my images do show up the first time I run the app after I clear the cache and I implemented a RequestListener and a ControllerListener which both turned up success.
Here is my current setup:
// Setting the collaborator image.
GenericDraweeHierarchy collaboratorPicHierarchy =
genericDraweeHierarchyBuilder
.setPlaceholderImage(
getInitialsAsDrawable(
collaborator.getUser().getInitials()
)
)
.setRoundingParams(new RoundingParams()
.setRoundAsCircle(true)
)
.build();
holder.collaborator.setHierarchy(collaboratorPicHierarchy);
holder.collaborator.setImageURI(
Uri.parse(AltEngine.formURL("user/getProfilePic/") +
accessToken + "/" +
collaborator.getUser().getUuid()
)
);
All this code lies inside an Adapter and in the Adapter's constructor I have initialized Fresco.
imagePipelineConfig = ImagePipelineConfig.newBuilder(this.context)
.build();
Fresco.initialize(this.context, imagePipelineConfig);
After a lot of searching in StackOverflow I found that the following Snippet could be used.
Fresco.getImagePipelineFactory().getMainDiskStorageCache().remove(new SimpleCacheKey(uri.toString()));
Fresco.getImagePipelineFactory().getSmallImageDiskStorageCache().remove(new SimpleCacheKey(uri.toString()));
I tried that in the onRequestSuccess of ImageRequest instance which I associated with the SimpleDraweeView but that resulted in the placeholder being shown everytime I refresh the ListView which is bad.
The next solution I found was from here Android - How to get image file from Fresco disk cache? which suggested that it might be necessary to implement my own DiskCacheConfig for Fresco to invalidate my DiskCache so I tried configured my DiskCache with the code I found in the SO question.
DiskCacheConfig diskCacheConfig = DiskCacheConfig.newBuilder().setBaseDirectoryPath(this.context.getCacheDir())
.setBaseDirectoryName("v1")
.setMaxCacheSize(100 * ByteConstants.MB)
.setMaxCacheSizeOnLowDiskSpace(10 * ByteConstants.MB)
.setMaxCacheSizeOnVeryLowDiskSpace(5 * ByteConstants.MB)
.setVersion(1)
.build();
imagePipelineConfig = ImagePipelineConfig.newBuilder(this.context)
.setMainDiskCacheConfig(diskCacheConfig)
.build();
Fresco.initialize(this.context, imagePipelineConfig);
Still the Cache is not updated by the image from the network.
I dont know what has gone wrong here. May be I've got Fresco wrong altogether. Any how I am stuck here and dont have a clue on how to proceed. I have been through the docs a couple of times and due to my hard luck I might have missed something important. Please point me in a proper direction.
This is basically the same question as was asked here: https://github.com/facebook/fresco/issues/124.
And in fact, you had about the right idea in the two lines you pasted above with the removal from disk cache. You just need to call them in the right place. onRequestSuccess is not the right place since that will nuke the image you just downloaded.
You want to remove the old entry from cache before even sending out a request for a new one. If Fresco finds the image on disk, it won't even send out a network request.
i'm using volley to load my images and cache them.
mImageLoader = new ImageLoader(getRequestQueue(context), mImageCache);
which mImageCache is a DiskLruImageCache.
volley fetches images from server by ImageRequest which extend the ImageRequest<Bitmap>
and in request class there is boolean that defines whether to cache the response or not
/** Whether or not responses to this request should be cached. */
private boolean mShouldCache = true;
and ImageRequest hasn't disabled mShouldCache.
as you can see the default value is true so after volley fetches an image caches it under the volley cache directory by diskBasedCache.
so now i have to cache bitmap one from ImageRequest and one from ImageLoader how can i disable ImageRequest cache ? or any other suggestions ?
You are making a mistake giving the ImageLoader a disk cache. Volley already has a shared disk cache for every response, be it an image are not, that works according to HTTP cache headers by default.
You are supposed to provide a memory bitmap cache to the ImageLaoder. Look at the documentation.
The reasoning for it is how Volley is designed. This is the image request logic for Volley:
Image with url X is added to the queue.
Check image memory cache (provided by you) - If available, return bitmap. quickest
Check shared disk cache - If available, check cache headers to see that image is still valid. If valid - add to memory bitmap cache and return. slower, but still pretty quick
This step means that either the image was in the disk cache but its cache headers are missing or expired, or the image wasn't available in the cache at all. Either way, Volley performs a network request and caches the response in both caches. slowest
So by providing a disk cache - you are both slowing down your app and taking up to twice as much disk space with redundant image saving.
Use a memory cache.