Android Picasso cache data - android

In my app I want to download images from url and show them in recyclerView. And basically everything is ok - when I download images, turn off wifi and mobile data - cached images are being displayed. Tried several times - it works perfectly. However ... after for example 3-4 hrs I tried again to launch app in offline mode and images were not displayed. Any idea what I'm doing wrong ? Here's my code in basic activity (onCreate) :
Picasso.Builder builder = new Picasso.Builder(getContext());
builder.downloader(new OkHttp3Downloader(getContext(),Integer.MAX_VALUE));
Picasso built = builder.build();
built.setIndicatorsEnabled(true);
built.setLoggingEnabled(true);
Then I download and cache images like this :
public void onResponse(Call<CallbackListPost> call, Response<CallbackListPost> response) {
CallbackListPost resp = response.body();
if (resp != null && resp.status.equals("ok")) {
post_total = resp.count_total;
displayApiResult(resp.posts);
controller = new RealmController(getActivity().getApplication());
controller.savePost(resp.posts);
for(Post post : resp.posts) {
for (final Attachment att : post.attachments) {
Picasso.with(getActivity())
.load(att.url)
.fetch(new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
Log.e(TAG, "onSuccess: " + att.url );
}
#Override
public void onError() {
}
});
}
}
Then in second activity I display images like this :
public View getView(int position, View convertView, ViewGroup parent) {
ImageView iv;
if(convertView == null) {
iv = new ImageView(mContext);
} else {
iv = (ImageView) convertView;
}
Picasso.with(mContext)
.load(att.get(position).url)
.noFade()
.resize(150,150)
.centerCrop()
.into(iv);
return iv;
}

Hello you can try this:
Picasso.with(mContext)
.load(att.get(position).url)
.noFade()
.resize(150,150)
.centerCrop()
.memoryPolicy(MemoryPolicy.NO_CACHE)
.networkPolicy(NetworkPolicy.NO_CACHE)
.into(iv);

I don't have much knowledge about Picasso.
I have a suggestion that you must go with Glide, an image caching tool.
Its very small library and very fast.
Simple use cases with Glide's generated API will look something like this:
// For a simple view:
#Override public void onCreate(Bundle savedInstanceState) {
...
ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
GlideApp.with(this).load("goo.gl/gEgYUd").into(imageView);
}
// For a simple image list:
#Override public View getView(int position, View recycled, ViewGroup container) {
final ImageView myImageView;
if (recycled == null) {
myImageView = (ImageView) inflater.inflate(R.layout.my_image_view, container, false);
} else {
myImageView = (ImageView) recycled;
}
String url = myUrls.get(position);
GlideApp
.with(myFragment)
.load(url)
.centerCrop()
.placeholder(R.drawable.loading_spinner)
.into(myImageView);
return myImageView;
}
It has auto cache config, which means we don't need to bother about the image cache.It loads perfectly after first use.
In Glide V4
Glide.with(context)
.load(“/user/profile/photo/path”)
.asBitmap()
.toBytes()
.centerCrop()
.into(new SimpleTarget<byte[]>(250, 250) {
#Override
public void onResourceReady(byte[] data, GlideAnimation anim) {
// Post your bytes to a background thread and upload them here.
}
});

If you refer to the documentation of the latest version of Picasso (2.71828) and figure out how Picasso handles it internally, you will understand why your images are NOT getting loaded from Disk/Cache.
Well explained answer is here https://stackoverflow.com/a/57114949/1508631.

Related

Getting error on loading image from https url using Picasso library

In my application I'm trying to load image from an https URL using Picasso library.I am unable to load image into ImageView. I am using Picasso 2.5.2 and I am setting the image as follows:
Picasso.with(mContext)
.load(GlobalVariable.movieDetails.get(0).getVideo_cover_image())
.placeholder(R.drawable.animation_placeholder)
.error(R.drawable.animation_placeholder)
.into(iv_image);
Try this
if (TextUtils.isEmpty(imageUrl) && !isValidUrl(imageUrl)) {
iv_image.setImageResource(R.drawable.default);
} else {
Picasso.with(context)
.load(imageUrl)
.resize(70, 70)//if you want resize image
.centerInside()
.into(iv_image, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
iv_image.setImageResource(R.drawable.default);
}
});
}
validate URL
public static boolean isValidUrl(String string) {
boolean b = Patterns.WEB_URL.matcher(string).matches();
return b;
}
Picasso provide a listener for image loading.
Use below code and check image loading status either Success or Error.
Picasso.with(mContext)
.load(GlobalVariable.movieDetails.get(0).getVideo_cover_image())
.placeholder(R.drawable.animation_placeholder)
.error(R.drawable.animation_placeholder)
.into(iv_imagenew,
new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
//Image Loaded
}
#Override
public void onError() {
//Error while Loading
}
});
please use resize(horizontalSize, verticalSize) method of picaso to resize image. may be your image size is to large thats why it will not load so , please try resize(horizontalSize, verticalSize)
Picasso.with(context)
.load(GlobalVariable.movieDetails.get(0).getVideo_cover_image())
.placeholder(R.drawable.animation_placeholder)
.error(R.drawable.animation_placeholder)
.into(iv_image);
.resize(600, 200) // resizes the image to these dimensions (in pixel). does not respect aspect ratio
.into(imageViewResize);

Image are not displaying from Cache memory using Picasso Library

I am using Picasso library for image download and displaying it in imageView. This library also store images in cache and memory. When my internet is turn on, i am able to view images on imageView. So i think, it should also be store in cache or file memory. Now my internet is turnOFF, but it doest not display to images. kindly have a look.
Picasso.with(context)
.load(url) .placeholder(R.drawable.defaultimg)
.networkPolicy(NetworkPolicy.OFFLINE)
.into(holder.imageview2, new ImageLoadedCallback(holder.loadingBar) {
#Override
public void onSuccess() {
if (holder.loadingBar != null) {
holder.loadingBar.setVisibility(View.GONE);
}
}
#Override
public void onError(){
holder.loadingBar.setVisibility(View.VISIBLE);
Picasso.with(context)
.load(url) .placeholder(R.drawable.defaultimg)
.into(holder.imageview2, new ImageLoadedCallback(holder.loadingBar) {
#Override
public void onSuccess() {
if (holder.loadingBar != null) {
holder.loadingBar.setVisibility(View.GONE);
}
}
#Override
public void onError() {
if (holder.loadingBar != null) {
holder.loadingBar.setVisibility(View.GONE);
}
}
});
}
});
Finally I resolved that issue. Thanks #dev.bmax
image url was not correct. There is bug in Picasso. If we have url like as
https://i.ytimg.com/vi/DMVEcfQmPOs/maxresdefault.jpg?500|700
Picasso is able to displaying image when internet TURN ON
but if we TURN OFF to internet, it does not decode the url. and not display the image also.
We have to remove ?500|700 then i was able to view image in OFFLine mode also.
//url.substring(0,url.indexOf("?"))
https://i.ytimg.com/vi/DMVEcfQmPOs/maxresdefault.jpg
Thanks!

Use a thumbnail as a placeholder for Picasso

From the UX point of view, it will be great to show the user a thumbnail first until the real image completes loading, then showing it to him, but Picasso uses only a resource file as the place holder like:
Picasso.with(context)
.load(url)
.placeholder(R.drawable.user_placeholder)
.into(imageView);
So, how can I use a thumbnail URL as the placeholder? , and if I should use Picasso twice, then how?
An issue is already opened on Picasso's github page with this request, but seems it won't be added to Picasso as per JakeWharton. So how could we do it with what's available in hand?
Thanks to raveN here & the comments on the original request on github, finally I've got a working solution:
Picasso.with(context)
.load(thumb) // thumbnail url goes here
.into(imageView, new Callback() {
#Override
public void onSuccess() {
Picasso.with(context)
.load(url) // image url goes here
.placeholder(imageView.getDrawable())
.into(imageView);
}
#Override
public void onError() {
}
});
The trick here is to get the drawable from the imageView (which is the thumbnail) after the first call & pass it as a placeholder to the second call
-- update --
I've made a blog post describing the whole scenario
You could write a simple helper which calls Picasso twice (as you mentioned).
I've not tested it, but it should go like
Picasso.with(context)
.load(thumbnailUrl)
.error(errorPlaceholderId)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
// TODO Call Picasso once again here
}
#Override
public void onError() {
}
);
There are a couple of different ways to get your Picasso called twice. One method I could think of (again, not tested) is
public static void loadImageWithCallback(String url, Callback callback) {
Picasso.with(context)
.load(url)
.error(errorPlaceholderId)
.into(imageView, callback);
}
public static void loadImage(String url) {
Picasso.with(context)
.load(url)
.error(errorPlaceholderId)
.into(imageView);
}
loadImageWithCallback("http://example.com/mythumbnail.jpg", new Callback() {
#Override
public void onSuccess() {
loadImage("http://example.com/myRealImage.jpg");
}
#Override
public void onError() {
}
}
Edit: All I know is that Picasso provides this callback mechanism. I'm using it in my app to hide a ProgressBar that is displayed until the image is loaded. I'll hide it in success or error callbacks - so you'll have the option to get notified when image loading is done. Then you can simply call it again. I hope the above approach works.
I originally used AbdelHady's solution but found that the larger image is only loaded after the thumbnail is done loading so I came up with this instead.
Assuming you have a utility class in your project;
public final class U {
public static void picassoCombo(final RequestCreator thumbnail,
final RequestCreator large,
final ImageView imageView) {
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
imageView.setImageBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
imageView.setImageDrawable(errorDrawable);
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
thumbnail.into(imageView);
}
};
imageView.setTag(target); // To prevent target from being garbage collected
large.into(target);
}
}
Usage:
U.picassoCombo(
Picasso.with(context)
.load("http://lorempixel.com/200/100/sports/1/")
.placeholder(R.drawable.ic_image_placeholder),
Picasso.with(context)
.load("http://lorempixel.com/800/400/sports/1/")
.error(R.drawable.ic_image_broken),
imageView
);
In the above example the placeholder is set first, the thumbnail url is set next, and regardless of whether the thumbnail request is done, successful, or failed, the large image request is set once it is done. If the large image request failed, then the error drawable is set.
The only issue is that if you use setIndicatorsEnabled(true) the debug indicators don't show for the large request. As far as I can tell this seems to be by design according to this issue convo

How do I get the resulting bitmap of a picture after it has been resized into an imageview with picasso

I'm trying to re-size a picture from my gallery to fit an imageview and save its bitmap after the fit so I can upload it to my Parse database on the press of an "add" button. Currently, when "add" is pressed, I check if the bitmap is null, and if it isn't, convert it to a Parsefile to be saved in my Parse database. Adding to the database works (I tested this without using Picasso), but I'm not sure how to get the bitmap if I use Picasso to resize and load. I tried creating a Target and using its callbacks, but I can't use .fit() on a target. I've resorted to using a callback, but I was hoping for a better way to achieve the saving of the bitmap.
Here's what I'm doing right now, trying to get the bitmap from the imageview after it's been loaded:
if(uri != null) {
Picasso.with(mContext).load(uri).skipMemoryCache().fit().centerCrop().into(imgPreview, new Callback() {
#Override
public void onSuccess() {
mBitmap = ((BitmapDrawable)imgPreview.getDrawable()).getBitmap();
}
#Override
public void onError() {
// TODO Auto-generated method stub
}
});
}
You can use a callback
Picasso.with(context)
.load(absolutePath)
.fit()
.noFade()
.centerInside()
.placeholder(R.drawable.image_holder)
.memoryPolicy(MemoryPolicy.NO_CACHE)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
// You can do anything here because your imageView now has the bitmap set
}
#Override
public void onError() {
}
});

displayImage and loadImage not caching the same file?

Following is my code in my class:
#Override
public void displayImageAsync(ImageView iv, MyImageLoadingListener listener)
{
ImageLoader.getInstance().displayImage(getImageUrl(), iv, listener);
}
#Override
public void loadImageAsync()
{
ImageLoader.getInstance().loadImage(getImageUrl(), new MyImageLoadingListener()
{
#Override
public void onImageLoaded(boolean completed, View view, Bitmap bitmap)
{
if (completed)
BusProvider.getInstance().post(new ImageMatchLoadedEvent(getThis(), bitmap));
}
});
}
after calling displayImageAsync (and succcessfully displaying the image), it seems, that loadImageAsync does not use the bitmap from the displayImageAsync call... Is that intended? After calling loadImageAsync once, the bitmap is cached and everything works as suppopsed...
Am I missing something? As you can see, both calls use exactly the same url...
Use picasso which is easy to use..
ImageView view = (ImageView) convertView.findViewById(R.id.ranking_prod_pic);
Picasso.with(context).load(url).into(view); //url is image url
//you can resize image if you want
/* Picasso.with(context) .load(url) .resize(50, 50) .centerCrop() .into(view) */
http://square.github.io/picasso/

Categories

Resources