Load image from URL to imageView as well as Cache - android

Hi i am new beginner in android. I want to insert image in imageView from URL but whenever one time it is loaded from URL in imageView then second time it should be insert without internet means it would be stored in cache as well.

for this you can use picasso Library
You can download it from Picasso Library site simply put this jar file into libs folder. It will manage all property of Image.
http://square.github.io/picasso/
String imgURL = "Your URL";
ivmage = (ImageView) findViewById(R.id.imageView1);
Picasso.with(MainActivity.this).load(imgURL).into(ivmage);

You can use Picasso Library.
By Using Picasso, The Advantages are
Handling ImageView recycling and download cancelation in an adapter.
Complex image transformations with minimal memory use.
Automatic memory and disk caching.
To load Image from Url
Picasso.with(context).load(url).into(imageView);
Refer this link for Api : Picasso

you can use Glide https://github.com/bumptech/glide
Glide.with(this).load("imageURl").into(imageView);

I suggest picasso library for doing this. here is the detailed documentation of picasso library.
ex:
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
or you can make use of volley's ImageLoader. here you can find the documentation for Volley's image loading.
ex :
// Retrieves an image specified by the URL, displays it in the UI.
ImageRequest request = new ImageRequest(url,
new Response.Listener<Bitmap>() {
#Override
public void onResponse(Bitmap bitmap) {
mImageView.setImageBitmap(bitmap);
}
}, 0, 0, null,
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
mImageView.setImageResource(R.drawable.image_load_error);
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(request);
if you are using volley. then you have to cache images manually. picasso will cache images by default.

Related

Display multiple image with Glide

I want to display one image into two different image views using glide.I know that i can simply use the code below to do it.
ImageView imageView = findViewById(R.id.header_image);
Glide.with(this).load(R.drawable.header_image).into(imageView);
ImageView imageView2 = findViewById(R.id.header_image);
Glide.with(this).load(R.drawable.header_image).into(imageView2);
But it requires to load the same image twice into memory and i don't want that due to memory issues.I want to load the image once and diaplay it into two image views.What can i do to achieve it?
You no need to worry about memory issue while using glide because glide has own caching system to optimize memory pls read this doc
Glide provides a number of options that allow you to choose how loads will interact with Glide’s caches on a per request basis.
Disk Cache Strategies
DiskCacheStrategy can be applied with the diskCacheStrategy method to an individual request. The available strategies allow you to prevent your load from using or writing to the disk cache or choose to cache only the unmodified original data backing your load, only the transformed thumbnail produced by your load, or both.
The default strategy, AUTOMATIC, tries to use the optimal strategy for local and remote images. AUTOMATIC will store only the unmodified data backing your load when you’re loading remote data (like from URLs) because downloading remote data is expensive compared to resizing data already on disk. For local data AUTOMATIC will store the transformed thumbnail only because retrieving the original data is cheap if you need to generate a second thumbnail size or type.
To apply a DiskCacheStrategy:
GlideApp.with(fragment)
.load(url)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imageView);
Loading only from cache
In some circumstances you may want a load to fail if an image is not already in cache. To do so, you can use the onlyRetrieveFromCache method on a per request basis:
GlideApp.with(fragment)
.load(url)
.onlyRetrieveFromCache(true)
.into(imageView);
If the image is found in the memory cache or in the disk cache, it will be loaded. Otherwise, if this option is set to true, the load will fail.
You can use following code to load an image once and display it in multiple imageviews.
Glide.with(this)
.asBitmap()
.load(R.drawable.header_image)
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<? super Bitmap> transition) {
imageview.setImageBitmap(resource);
imageview2.setImageBitmap(resource);
}
});
If you are using latest version of Glide then create RequestOptions like
private RequestOptions simpleOptions = new RequestOptions()
.centerCrop()
.placeholder(R.color.color_gray)
.error(R.color.color_gray)
.diskCacheStrategy(DiskCacheStrategy.RESOURCE);
Use RequestOptions to load image with set properties
Glide.with(context)
.load(url)
.apply(simpleOptions)
.into(imageView);
Or maybe this way…
RequestBuilder<Drawable> builder = Glide.with(this).load(drawableResId);
builder.into(imageView0)
builder.into(imageView1)
try this way ...
setImage(R.drawable.header_image,imageView ,imageView2 );
void setImage(int image, ImageView... imageView) {
for (ImageView imageView : imageView) {
if (imageView != null) {
Glide.with(this).load(image).into(imageView);
}
}
}

Loading image in ImageView using volley library

I stored the path to my images in mysql db and was not sure if there's a way to load them in an imageView using volley library.
I'm able to parse string as json and display it in textView using volley string request queue but wasn't sure how I can get the path to display as image in my imageView. I would like to fetch the image using id.
Thanks in advance!
I always use the Glide to load images like this. Simply return the path like you do any other string. There is no need to load a bitmap with Volley, using Glide for this is simpler and better. Glide will handle for example image caching amongst other things.
This is all you need except from the Volley part.
ImageView imageView = findViewById(R.id.image);
String url = "www.foobar.com/" + path;
Glide.with(context).load(url).into(imageView);
Recently, I used Picasso library in my project and it worked fine and smooth. You can easily Load Image to ImageView from Url by using Picasso. Moreover, you can resize the original image to your desire size.
Example:
String mURL = "https:\/\/c.tribune.com.pk\/2017\/12\/1593389-vanga-1514310781-708-160x120.jpg";
ImageView Icon = (ImageView) findViewById(R.id.icon);
Picasso.with(context).load(mURL).resize(72, 72).into(icon);
Note: Using Picasso first you must import its library.
I used this: compile 'com.squareup.picasso:picasso:2.5.2'
use glide to display your image or you can use picasso
new ImageRequest(
url,
listener,
maxWidth,
maxHeight,
decodeConfig,
errorListener);
Response.Listener<Bitmap> listener = new Response.Listener<Bitmap>() {
#Override
public void onResponse(Bitmap bitmap) {
//here you set the bitmap to imageview
} };

Cache images local, from google firebase storage

I am searching for a way, to cache images from the storage on google firebase platform. For now, I can download images, and show these to users, but I am not able to cache this, and access, even without internet connection. The database can be accessed offline. So I thought, there would be a way for storage too. I don't want to download every single image to storage, cause then I would need to check everytime, if the image is still up to date, it may be changed. Here are few links, what I could find, but no answer for my question. Maybe someone know a workaround, or a way how to accomplish it. Thanks!
Download files:
https://firebase.google.com/docs/storage/android/download-files
Cache (offline) database:
https://firebase.google.com/docs/database/android/offline-capabilities
UPDATE 1
Here is how I "cache" files with picasso, I added activity, that cares the download:
Picasso.with(getApplicationContext())
.load(uri.toString())
.networkPolicy(NetworkPolicy.OFFLINE)
.into(image1);
Any help is welcome. Thanks!
I'm afraid the Firebase SDK doesn't provide image caching by itself. But there are several great libraries that could do it for you. They download image, show it in an ImageView and cache it in a single line of code. Just request the Firebase for an image download url and feed it to the image caching library.
Something like this, if you choose Picasso as a caching library:
storageRef.child("users/me/profile.png").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// Got the download URL for 'users/me/profile.png'
// Pass it to Picasso to download, show in ImageView and caching
Picasso.with(context).load(uri.toString()).into(imageView);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
UPD: To use disk caching with Picasso you need to explicitly setup OkHttpDownloader. Look here How do I use disk caching in Picasso?
Thanks to #ATom for notice. Api has changed, and FirebaseUI 3.0 now uses Glide 4.x
Here is updated sample:
To load an image from a StorageReference, first register in your
AppGlideModule:
#GlideModule
public class MyAppGlideModule extends AppGlideModule {
#Override
public void registerComponents(Context context, Glide glide, Registry registry) {
// Register FirebaseImageLoader to handle StorageReference
registry.append(StorageReference.class, InputStream.class,
new FirebaseImageLoader.Factory());
}
}
Then you can load a StorageReference into an ImageView:
// Reference to an image file in Cloud Storage
StorageReference storageReference = ...;
// ImageView in your Activity
ImageView imageView = ...;
// Download directly from StorageReference using Glide
// (See MyAppGlideModule for Loader registration)
GlideApp.with(this /* context */)
.load(storageReference)
.into(imageView);
And don't forget to add dependency in your build.gradle:
implementation 'com.firebaseui:firebase-ui-:3.1.0'
Answer source on GitHub
Old answer:
FirebaseUI 1.0 now released. Storage example has class FirebaseImageLoader
Images displayed using FirebaseImageLoader are cached by their path in
Firebase Storage, so repeated loads will be fast and conserve
bandwidth.
// Reference to an image file in Firebase Storage
StorageReference storageReference = ...;
// ImageView in your Activity
ImageView imageView = ...;
// Load the image using Glide
Glide.with(this /* context */)
.using(new FirebaseImageLoader())
.load(storageReference)
.into(imageView);
I had the same issue. Tried all possible ways but couldn't fix that. I think the problem lies with the links generated by firebase storage. Picasso generally caches the images it loads. I have tried other cloud services like cloudinary, LibPixel whose links end with image format (Eg:.jpg) and picasso caches these link images. While firebase links end with token numbers. Strange thing it fails!

Picasso doesn't cache image on disk

I have to use custom OkHttpClient so I can add headers to the image requests. The problem is Picasso won't cache any images on disk because of this. I've used setIndicatorsEnabled(true) to check caching and I see only red indicators. When I use default OkHttpDownloader all is ok. Below is my Picasso initialization code. So does anyone encounter the same problem?
public static void init(Context context) {
Picasso.Builder builder = new Picasso.Builder(context);
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new AuthInterceptor());
Downloader downloader = new OkHttpDownloader(client);
Picasso.setSingletonInstance(builder.downloader(downloader).build());
Picasso.with(context).setIndicatorsEnabled(true);
}
Also my image download code
public static void load(final ImageView imageView, final Image image) {
Picasso.with(imageView.getContext())
.load(image.getUrl())
.resize(400, 0)
.memoryPolicy(MemoryPolicy.NO_CACHE)
.into(imageView);
}
Ah since this is happening when you change headers, you are most probably not setting the Cache-Control header
According to Jake wharton (One of the developer of Picasso)
Picasso doesn't have a disk cache. It delegates to whatever HTTP
client you are using for that functionality (relying on HTTP cache
semantics for cache control). Because of this, the behavior you seek
comes for free
Taken from Jake Wharton's answer here
Also,
If you never see a blue indicator, it's likely that your remote images
do not include proper cache headers to enable caching to disk

Picasso not loading updated image from Web in android

I'm using Picasso in android app loading image from web url, But I see image is not updated when I updated image on web.
Picasso.with(context).load("http://testServer.com/Images/sponsor.png").into(imageView1);
Thanks in advance.
Picasso uses a cache mechanism, so the same image is not re-downloaded twice.
If you need to bypass this cache, you can change memory or network policy to do this.
Picasso has builtin caching so the image cached automaticly. try invalidating.
example:
Picasso.with(getActivity()).invalidate(file);
public void loadImage(ImageView imageView, String image_url,Contextcontext)
{
try
{
Picasso.with(context)
.load(image_url)
.memoryPolicy(MemoryPolicy.NO_CACHE)
.networkPolicy(NetworkPolicy.NO_CACHE)
.placeholder(R.drawable.default_image)
.into(imageView);
}
catch(Exception ex)
{
ex.toString();
}
}
try to download aquery library see here https://code.google.com/p/android-query/wiki/ImageLoading

Categories

Resources