I have one ImageView and one image loaded in it with Glide:
Glide.with(ImageView.getContext())
.load(url)
.dontAnimate()
.placeholder(R.drawable.placeholder)
.signature(stringSignature)
.into(new GlideDrawableImageViewTarget(ImageView) {
#Override
public void onResourceReady(GlideDrawable drawable, GlideAnimation anim) {
super.onResourceReady(drawable, anim);
progressBar.setVisibility(View.GONE);
}
});
and when I want refresh the image, I run this same code again only with new signature. It's working perfectly, but when new loading is started, the visible image is gone immediately.
Question
Is possible keep the image in ImageView and replace it after new image is downloaded?
That's the expected behavior.
Each time you call .load(x), Glide call .clear() on the target and its associated request.
That's how Glide is able to handle its pool of Bitmaps, otherwise it would have no way to know when to recycle a Bitmap.
In order to implement this, you need to switch between two Targets, here is the core idea :
public <T> void loadNextImage(#NonNull T model,
#NonNull BitmapTransformation... transformations) {
//noinspection MagicNumber
int hash = model.hashCode() + 31 * Arrays.hashCode(transformations);
if (mLastLoadHash == hash) return;
Glide.with(mContext).load(model).asBitmap().transform(transformations).into(mCurrentTarget);
mLastLoadHash = hash;
}
Target mCurrentTarget;
private class DiaporamaViewTarget extends ViewTarget<ImageView, Bitmap> {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
mLoadedDrawable = new BitmapDrawable(mImageView.getResources(), resource);
// display the loaded image
mCurrentTarget = mPreviousTarget;
You can set loaded Drawable as placeholder in next loading, like this:
private Drawable placeholder = ContextCompat.getDrawable(ctx, R.drawable.placeholder);
public void loadImage(String url, ImageView imageView) {
Glide.with(imageView.getContext())
.load(url)
.placeholder(placeholder)
.into(new GlideDrawableImageViewTarget(imageView) {
#Override
public void onResourceReady(GlideDrawable drawable, GlideAnimation anim) {
super.onResourceReady(drawable, anim);
placeholder = drawable;
}
});
}
Related
I cannot display the image downloaded from the Internet as annotation. I am implementing the following code and Picasso library. However, if I use a local image, it works. Thanks in advance for any help.
private void createAnnotation(int id, double lat, double lon, String caption, String photoUrl) {
SKAnnotation annotation = new SKAnnotation(id);
SKCoordinate coordinate = new SKCoordinate(lat, lon);
annotation.setLocation(coordinate);
annotation.setMininumZoomLevel(5);
SKAnnotationView annotationView = new SKAnnotationView();
View customView =
(LinearLayout) ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.annotation_photo_and_text, null, false);
// If width and height of the view are not power of 2 the actual size of the image will be the next power of 2 of max(width,height).
//annotationView.setView(findViewById(R.id.customView));
TextView tvCaption = (TextView) customView.findViewById(R.id.annotation_photo_caption);
tvCaption.setText(caption);
ImageView ivPhoto = (ImageView) customView.findViewById(R.id.annotation_photo);
Picasso.with(getApplicationContext())
.load(photoUrl)
.resize(96, 96)
//.centerCrop()
.into(ivPhoto);
//ivPhoto.setImageResource(R.drawable.hurricanerain);
annotationView.setView(customView);
annotation.setAnnotationView(annotationView);
mapView.addAnnotation(annotation, SKAnimationSettings.ANIMATION_NONE);
}
Picasso loads images from the internet asynchronously. Try adding the image to the Annotation after it has been downloaded. You can use a Target to listen for the image download completion:
ImageView ivPhoto = (ImageView) customView.findViewById(R.id.annotation_photo);
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
ivPhoto.setImageBitmap(bitmap);
annotationView.setView(customView);
annotation.setAnnotationView(annotationView);
mapView.addAnnotation(annotation, SKAnimationSettings.ANIMATION_NONE);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {}
};
ivPhoto.setTag(target);
Picasso.with(getApplicationContext())
.load(photoUrl)
.resize(96, 96)
.into(target);
try activity context in place of applicationcontext. It may work for you.
What if you try to load image using Target object, and then set downloaded bitmap to your ImageView?
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
// loading of the bitmap was a success
// TODO do some action with the bitmap
ivPhoto.setImageBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
// loading of the bitmap failed
// TODO do some action/warning/error message
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
ivPhoto.setTag(target);
Picasso.with(getApplicationContext())
.load(photoUrl)
.resize(96, 96)
.into(target);
I have this method, everything is worked perfectly but images always got from server and not load from cache! what happened ?
public static void makeImageRequest(String Unique_ID, final View parentView, final int id) {
String url = FILE_UPLOAD_FOLDER + Unique_ID + ".png";
final int defaultImageResId = R.drawable.user;
// Retrieves an image specified by the URL, displays it in the UI.
ImageCacheManager.getInstance().getImage(url, new ImageListener() {
#Override
public void onErrorResponse(VolleyError error) {
ImageView imageView = (ImageView) parentView.findViewById(id);
imageView.setImageResource(defaultImageResId);
}
#Override
public void onResponse(ImageContainer response, boolean isImmediate) {
if (response.getBitmap() != null) {
ImageView imageView = (ImageView) parentView.findViewById(id);
imageView.setImageBitmap(response.getBitmap());
} else if (defaultImageResId != 0) {
ImageView imageView = (ImageView) parentView.findViewById(id);
imageView.setImageResource(defaultImageResId);
}
}
});
}
Just use Picasso instead ImageCacheManager. Picasso is a powerful image downloading and caching library for Android. Images add much-needed context and visual flair to Android applications. Picasso allows for hassle-free image loading in your application—often in one line of code!
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Here also can manage whether the image is successfully downloaded or it fails:
Picasso.with(context)
.load("http://i.imgur.com/DvpvklR.png")
.into(imageView, new Callback() {
#Override
public void onSuccess() {
// your code
}
#Override
public void onError() {
// your code
}
});
You should only add this line in your gradle:
compile 'com.squareup.picasso:picasso:2.5.2'
Hope it helps!
I'm trying to use Glide to get a SVG resource from a URL, but I don't know how to get a Bitmap object instead of loading it in into a View.
The reason for that is that I need to load some SVG files on a Widget.
I used this example: https://stackoverflow.com/a/30938082/3346625
UPDATE 1:
Setup GenericRequestBuilder
final RemoteViews fViews = views;
final int fViewId = viewId;
Runnable myRunnable = new Runnable() {
#Override
public void run() {
GenericRequestBuilder<Uri, InputStream, SVG, Bitmap> requestBuilder;
requestBuilder = Glide.with(mContext)
.using(Glide.buildStreamModelLoader(Uri.class, mContext), InputStream.class)
.from(Uri.class)
.as(SVG.class)
.transcode(new SvgBitmapTranscoder(), Bitmap.class)
.sourceEncoder(new StreamEncoder())
.cacheDecoder(new FileToStreamDecoder<SVG>(new SvgDecoder()))
.decoder(new SvgDecoder())
.placeholder(R.drawable.ic_launcher)
.error(R.drawable.no_icon)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.load(Uri.parse(url));
requestBuilder.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
fViews.setImageViewBitmap(fViewId, resource);
}
});
}
};
mainHandler.post(myRunnable);
I had to use a Runnable as requestBuilder.into needs to run on the main thread.
How can I get a Bitmap to later use it with a RemoteView?
Try this:
.transcode(new SvgBitmapTranscoder(), Bitmap.class)
.into(new SimpleTarget<Bitmap>(sizeW, sizeH) {
#Override public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
// update RemoteViews with resource
}
})
SvgBitmapTranscoder should be fairly trivial if there's an svg.renderToBitmap() method.
I'm trying to load an url into an ImageView but Target doesn't seem to work like what I found told me. Below is my code:
ImageView methodButton= (ImageView) View.inflate(context, R.layout.view_home_scroll_view_image, null);
setMethodPicture(sectionModel.getContent().get(0).getThumbnail(), methodButton);
methodsContainer.addView(methodButton);
and
private void setMethodPicture(final String methodPicture, final ImageView methodButton){
methodButton.setBackgroundColor(0x000000);
if (!StringUtils.isEmpty(methodPicture)) {
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
methodButton.setImageBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
#Override
public boolean equals(Object o) {
return methodPicture.equals(o);
}
#Override
public int hashCode() {
return methodPicture.hashCode();
}
};
Picasso.with(context).load(methodPicture).into(target);
}
}
This doesn't load the picture to the imageView, but when i do this,
ImageView methodButton= (ImageView) View.inflate(context, R.layout.view_home_scroll_view_image, null);
methodButton.setBackgroundColor(0x000000);
Picasso.with(context).load(sectionModel.getContent().get(0).getThumbnail()).into(methodButton);
methodsContainer.addView(methodButton);
it loads the picture.
I want to do the first one so I can change the Bitmap I get before I put it in the ImageView, like changing the width and height, but basing on the original dimensions.
I found the issue, Picasso holds a Weak Reference to the Target. The correct answer can be found here: onBitmapLoaded of Target object not called on first load
Use Glide instead, it provide predefine constrain options which you can add with it
https://github.com/bumptech/glide
I was using Universal Image Loader library to load a set of images and TouchImageView to allow zooming. I decided to replace Universal Image Loader with picasso. Everything worked fine except now the image zooms around a frame which is slightly bigger than the image.
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.item_pager_image, view, false);
assert imageLayout != null;
TouchImageView imageView = (TouchImageView) imageLayout.findViewById(R.id.image);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
spinner.setVisibility(View.INVISIBLE);
Picasso.with(getApplicationContext()).setIndicatorsEnabled(false);
Picasso.with(getApplicationContext()).load(images[position]).into(imageView,new Callback() {
#Override
public void onSuccess() {
spinner.setVisibility(View.GONE);
}
#Override
public void onError() {
}
});
view.addView(imageLayout, 0);
return imageLayout;
I have been breaking my head over a few hours for this. Is this some issue TouchImageView has with Picasso? Any help would be appreciable. Thanks.
Mahram Foadi posted here a great solution that work for me too:
Picasso.with(context).load (someUri).into(new Target () {
#Override
public void onBitmapLoaded (final Bitmap bitmap,
final Picasso.LoadedFrom loadedFrom) {
someTouchImageView.setImageBitmap (bitmap);
}
#Override
public void onBitmapFailed (final Drawable drawable) {
Log.d(TAG, "Failed");
}
#Override
public void onPrepareLoad (final Drawable drawable) {
someTouchImageView.setImageDrawable (drawable);
}
});
Hope this helps other people like us to use TouchImageView with Picasso ;)
I figured out the whole issue somehow got fixed when I set the image width and height from wrap_content to fill_parent.
Here is if you are using Glide. Glide is faster in loading than picasso and cheaper in memory consuming
Glide.with(context).load(url).asBitmap().into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
someTouchImageView.setImageBitmap(resource);
}
});
For those who still run into this problem.
As inspired by a comment in this issue:
It's because needs View size and it's not available in TouchImageView implementation before bitmap is set
Load the image after the TouchImageView is created using .post().
Kotlin code:
touchImageView.post { // Load the image when the view is ready
Picasso.get()
.load(file)
.placeholder(R.drawable.image_placeholder)
.into(touchImageView)
}
Java code:
// Load the image when the view is ready
touchImageView.post(new Runnable() {
#Override
public void run() {
Picasso.get()
.load(file)
.placeholder(R.drawable.image_placeholder)
.into(touchImageView)
}
});