I'm loading a picture from the network for an ImageView but the imageView is not immediately showing up.
My code is:
protected void onStart() {
iv_head.setImageDrawable(this.getResources().getDrawable(R.drawable.default_head));
BaseController.getImageForUrl(HttpConstant.SERVER_HEAD + "/" +customer.getExtra().getLogo(), iv_head, R.drawable.default_head);
super.onStart();
}
//获取图片的数据
public static void getImageForUrl(String url, final ImageView imageView, final int errorImage) {
ImageRequest imageRequest = new ImageRequest(
url, new Response.Listener<Bitmap>() {
#Override
public void onResponse(final Bitmap response) {
imageView.setImageBitmap(response);
imageView.invalidate();
}
}, 0, 0, Bitmap.Config.RGB_565, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
imageView.setImageResource(errorImage);
}
});
QueueManager.getRequestQueue().add(imageRequest);
}
I'm sure that it is loading the Bitmap but ImageView is still giving problems.
If I click anywhere on the screen, then ImageView shows. Does anyone know what's happening?
Use
imageView.setImageDrawable(new BitmapDrawable(imageView.getResources(), response));
instead
imageView.setImageBitmap(response);
imageView.invalidate();
I would try to use the Picasso library instead...then your code would be like this:
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
nice and simple, no headaches, no reinvention of the wheel. Good luck!
Related
I have a BackgroundImageActivity that load background image using Picasso. But when I go back to home (onStop() called in BackgroundImageActivity) and go into another instance of this activity, which is supposed to load another background image, but at first 2 seconds, it still shows the image from previous BackgroundImageActivity. Is this some kind of cache?
How I can clear this image so that whenever I go into a new instance of BackgroundImageActivity, i don't see the image from previous one?
public class BackgroundImageActivity extends Activity {
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initBackground();
}
#Override
protected void onStop() {
super.onStop();
Picasso.invalidate(imageUrl, getApplicationContext());
}
private void initBackground() {
...
}
private void setBg(final String imageUrl, final int bg) {
this.imageUrl = imageUrl;
final RequestCreator picassoRequest = Picasso.load(imageUrl, bg).memoryPolicy(MemoryPolicy.NO_CACHE);
targetReference = new Target() {
#Override
public void onBitmapLoaded(final Bitmap bitmap, final Picasso.LoadedFrom from) {
...
}
#Override
public void onBitmapFailed(final Drawable errorDrawable) {
...
}
#Override
public void onPrepareLoad(final Drawable placeHolderDrawable) {
...
}
};
picassoRequest.placeholder(bg).error(bg).into(targetReference);
}
}
Thanks!!!
Use this piece of code while loading the image.
Picasso.with(getContext())
.load(data.get(pos)
.getFeed_thumb_image())
.memoryPolicy(MemoryPolicy.NO_CACHE)
.into(image);
Picasso set the image to ImageView directly without caching in the background. This makes the app lightweight also.
I'm trying to use an IntentService for processing and uploading images that's running in a different process to have more memory. I'm Using also Picasso to load the Image. When the Image is small the bitmap is loaded successfully and uploaded, however if the image is big the IntentService is terminated before Picasso is done loading It.
Picasso have to run on UIThread
Here is the code.
private void downloadImage(File file) {
final Uri uri = Uri.fromFile(file);
Handler uiHandler = new Handler(Looper.getMainLooper());
uiHandler.post(new Runnable() {
#Override
public void run() {
Picasso.with(NewImageProcessingService.this).load(uri).transform(new ImageLoadingUtil.DecreaseQualityTransformation(imageQuality)).into(NewImageProcessingService.this);
}
});
}
#Override
protected void onHandleIntent(Intent intent) {
File file = (File) intent.getSerializableExtra(KEY_IMAGE_FILE);
imageQuality = ImagesUtils.IMAGE_QUALITY
.values()[intent.getIntExtra(IMAGE_QUALITY, ImagesUtils.IMAGE_QUALITY.DEFAULT.ordinal())];
downloadImage(file);
}
This question is quite old, but if anyone steps by. The Target is getting garbage collected before it can show the bitmap.
Use it like this
public class BitmapLoader {
public static Target getViewTarget(final OnImageLoadingCompleted onCompleted) {
return new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
onCompleted.imageLoadingCompleted(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
}
}
You need to have a strong reference to the Target so have a field in your IntentService holding it e.g.
private Target viewTarget;
viewTarget = BitmapLoader.getViewTarget(bitmap -> {
// do stuff with the bitmap
});
new Handler(Looper.getMainLooper()).post(() -> Picasso.with(getApplicationContext()).load(object.getImageUrl()).into(viewTarget));
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 want to show a fade effect when image is loading on Imageview. I am using picasso to cache image and display in image view. I have searched alot for this but couldnt find any solution.
I have used earlier before and i know in some version they had .fade(int Duration) method to fade image while loading but i couldnt find this method anymore.
Here is what i am doing now
Picasso.with(context)
.load(viewHolder.data.imageList.get(0).url)
.networkPolicy(NetworkPolicy.OFFLINE)
.placeholder(R.drawable.a_place_holder_list_view)
.error(R.drawable.a_place_holder_list_view)
.into(viewHolder.ivUser, context.loadImage(viewHolder.ivUser, viewHolder.data.imageList.get(0).url));
public Callback loadImage(RoundedImageView ivUser, String url) {
return new callback(ivUser, url);
}
public class callback implements Callback {
RoundedImageView imageView;
String url;
public callback(RoundedImageView imageView, String url) {
this.imageView = imageView;
this.url = url;
}
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(BaseActivity.this)
.load(url)
.placeholder(R.drawable.a_place_holder_list_view)
.error(R.drawable.a_place_holder_list_view)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Log.v("Picasso", "Could not fetch image");
}
});
}
}
Please help me i have been stuck in this for quite long time.
Thanks in advance.
Quoting Jake Wharton's answer here:
If the image comes from anywhere except the memory cache the fade
should be automatically applied.
If you check the PicassoDrawable class
boolean fade = loadedFrom != MEMORY && !noFade;
if (fade) {
this.placeholder = placeholder;
animating = true;
startTimeMillis = SystemClock.uptimeMillis();
}
.
.
.
#Override public void draw(Canvas canvas) {
if (!animating) {
super.draw(canvas);
} else {
.
.
.
fade effect is already applied for images loaded from n/w and not memory/cache
and FADE_DURATION = 200f; //ms
To force fade, again quoting jake wharton's answer here:
You can specify noFade() and then always play an animation in the
image loaded callback. You can also rely on the callback being called
synchronously to determine if an animation needs played.
final AtomicBoolean playAnimation = new AtomicBoolean(true);
Picasso.with(context).load(..).into(imageView, new Callback() {
#Override public void onLoad() {
if (playAnimation.get()) {
//play fade
Animation fadeOut = new AlphaAnimation(0, 1);
fadeOut.setInterpolator(new AccelerateInterpolator());
fadeOut.setDuration(1000);
imageView.startAnimation(fadeOut);
Animation fadeOutPlaceholder = new AlphaAnimation(1, 0);
fadeOutPlaceholder.setInterpolator(new AccelerateInterpolator());
fadeOutPlaceholder.setDuration(1000);
placeHolderImageView.startAnimation(fadeOutPlaceholder);
}
}
//..
});
playAnimation.set(false);
You can simply do
Picasso.with(context).load(url).fetch(new Callback(){
#Override
public void onSuccess() {
imageView.setAlpha(0f);
Picasso.with(context).load(url).into(imageView);
imageView.animate().setDuration(300).alpha(1f).start();
}
#Override
public void onError() {
}
});
I do this:
Picasso.get().load(url).fit().noFade().centerInside().into(imageView, new Callback() {
#Override
public void onSuccess() {
imageView.setAlpha(0f);
imageView.animate().setDuration(200).alpha(1f).start();
}
#Override
public void onError(Exception e) {
}
});
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