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!
Related
I am trying to show a loading icon when the image hasn't loaded yet and hide the loading icon when the image is ready. I am using Fresco library and I used the code below successfully to implement what I want:
private void loadImage(ImageView imageview,final ImageView videoicon, final GifTextView progressbar, Uri uri,final boolean video,final boolean child,boolean isConnectivity)
{
if (child)
{
if (isConnectivity)
progressbar.setBackgroundResource(Theme.Icons.LoadingChild);
}
else
{
progressbar.setBackgroundResource(Theme.Icons.LoadingMain);
}
SimpleDraweeView imageDrawee = (SimpleDraweeView) imageview;
ControllerListener controllerListener = new BaseControllerListener<ImageInfo>() {
#Override
public void onFinalImageSet(String id, #Nullable ImageInfo imageInfo, #Nullable Animatable anim) {
if (imageInfo == null) {
return;
}
progressbar.setVisibility(View.GONE);
if (video)
{
if (child)
{
videoicon.setImageResource(Theme.Icons.MediaGalleryVideoIcon);
}
else
{
linearlayout_mediagalleryvideoicon.setVisibility(View.VISIBLE);
videoicon.setImageResource(Theme.Icons.MediaGalleryVideoIcon);
}
}
}
#Override
public void onIntermediateImageSet(String id, #Nullable ImageInfo imageInfo) {
//FLog.d("Intermediate image received");
}
#Override
public void onFailure(String id, Throwable throwable) {
//FLog.e(getClass(), throwable, "Error loading %s", id)
}
};
DraweeController controller = Fresco.newDraweeControllerBuilder()
.setControllerListener(controllerListener)
.setOldController(imageDrawee.getController())
.setUri(uri)
.build();
imageDrawee.setController(controller);
}
My problem is that when I close the Fragment, I can see from the Android Monitor that the DraweeController continue using CPU. When I open 20-30 Fragment that contain one image, my application crashes because of heavy CPU load.
How to overcome this problem?
The problem wasn't with Fresco library, but with the library I used to display GIF images.
My problem statement is to load the images from the server.
Now I have used picasso inside the custom adapter.
The image which I am downloading its size is approximately 100kb
not more than that.But instead of displaying the image white background is
been displayed.
To check error I have used callback but somehow the callback is not working
I mean the callback is never getting called.
Below is my code
#Override
public void onBindViewHolder(FolderListAdapter.Viewholder holder, int position) {
userDetails=userList.get(position);
//Context context=);
if(userDetails.getLogo()!=null && !userDetails.getLogo().isEmpty()) {
Context context=holder.cardProfilePic.getContext();
Picasso.with(context)
.load(userDetails.getLogo())
.fit()
.into(holder.cardProfilePic, new Callback() {
#Override
public void onSuccess() {
Log.d("succes","success");
}
#Override
public void onError() {
Log.d("failure","failure");
}
});
}
if(userDetails.getBanner()!=null && !userDetails.getBanner().isEmpty()) {
Picasso.with(context)
.load(userDetails.getBanner())
.resize(300,300)
.into(holder.cardBackgroundPic);
}
if(userDetails.getPersonName()!=null && !userDetails.getPersonName().isEmpty()) {
holder.username.setText(userDetails.getPersonName());
}
if(userDetails.getDesignation()!=null && !userDetails.getDesignation().isEmpty()) {
holder.userRole.setText(userDetails.getDesignation());
}
}
I'm displaying multiple images from our server as a slideshow with a ImageSwitcher. Before the ImageSwitcher gets initialized I want to preload the images with Picasso library.
I want to say that I use Picasso with an interceptor, because our server requires Basic Authentication for the images.
My current preloading:
final int[] downloadedCounter = {0};
for (int i = 0; i < images.size(); i++) {
final SlideshowImage image = images.get(i);
PicassoUtils.getPicassoWithBasicAuthorizationFrom(user, getContext())
.load(image.getImageUrl())
.fetch(new Callback() {
#Override
public void onSuccess() {
downloadedCounter[0]++;
if (downloadedCounter[0] == images.size()) {
callback.downloadFinished();
}
}
#Override
public void onError() {
}
});
}
And that is my ImageSwitcher:
ImageView image = (ImageView) this.getNextView();
PicassoUtils.getPicassoWithBasicAuthorizationFrom(user, getContext())
.load(imageUrl)
.noFade()
.into(image, new Callback() {
#Override
public void onSuccess() {
showNext();
}
#Override
public void onError() {
}
});
But the problem is, that it won't get cached, because when I use .networkPolicy(NetworkPolicy.OFFLINE) on Picasso in my ImageSwitcher nothing gets loaded.
And everytime i call showNext() in my ViewSwitcher the used memory of the device rises a bit.
I'm creating an application where the user selects one item from a recycler view and this starts the download of a group of images.
I'm using universal image loader's loadImage method to fetch images for me which is working very well.
The problem is,if the user wants to cancel downloading this group of images (can be very network consuming) I cannot find a way to make ui stop only some of the images.
I'm aware of the method ImageLoader.cancelDisplayTask(), but as I'm using loadImage I have no ImageView or ImageAware available to send as a parameter to this task.
Also ImageLoader.stop() or ImageLoader.pause() stops all current downloads and I want to stop only the ones selected by the user.
How can I achieve this?
PS: A suggestion to some future development would be returning a pointer of the download task when using loadImage method. Maybe I'll look it myself when I have some time to contribute to this awesome library.
Here's my code for downloading an image.
private void downloadFile(final URL downloadURL,
final URL destinationURL,
final boolean isThumbnail,
final MyDownloadListener listener) {
final NewsData thisClass = this;
final ImageLoader il = ImageLoader.getInstance();
File imageFile = il.getDiskCache().get(destinationURL.toString());
if (imageFile.exists()) {
fallDownloadCompleted(this, isThumbnail);
return;
}
il.stop();
il.loadImage(
downloadURL.toString(),
null,
Application.getAppDisplayOptions(),
new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
if (listener != null) {
listener.onLoadingStarted(thisClass);
}
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
fallDownloadFail(thisClass, failReason, isThumbnail);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
try {
il.getDiskCache().save(destinationURL.toString(), loadedImage);
if (isToday()) deleteImageFile(imageUri);
} catch (IOException e) {
deleteImageFile(imageUri);
fallDownloadFail(
thisClass,
new FailReason(FailReason.FailType.IO_ERROR, new Throwable()),
isThumbnail);
return;
}
fallDownloadCompleted(thisClass, isThumbnail);
}
},
new ImageLoadingProgressListener() {
#Override
public void onProgressUpdate(String imageUri, View view, int current, int total) {
float progress = 0;
if (total > 0 && numberOfTotalPages > 0) {
if (!isThumbnail) {
progress = numberOfAvailablePages / (float) numberOfTotalPages;
progress += (current / (float) total) / numberOfTotalPages;
} else {
progress = current / (float) total;
}
}
if (listener != null) {
listener.onProgressUpdate(thisClass, progress);
}
}
});
}
private ArrayList<ImageLoader> images = new ArrayList<ImageLoader>();
images.remove():
? Not familiar with ImageLoader class but I hope this helps
These might help
android: Universal Image Loader get drawable from string array
How to change array list to string array for using Universal Image Loader?
https://github.com/nostra13/Android-Universal-Image-Loader/issues/109
I managed to solve this issue with a small workaround.
I couldn't find a way to cancel a particular ImageLoader.loadImage() so what I had to do was use the normal ImageLoader.displayImage() by passing a NonViewAware class in place of the image view required as a parameter.
I then added this NonViewAware into an ArrayList<NonViewAware> to keep track of which images were being downloaded.
Finally when I wanted to cancel a display task I just called ImageLoader.cancelDisplayTask(NonViewAware) with one of the stored items from the list.
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)
}
});