Abolfazl-sh Abolfazl-sh - 3 months ago 22
Android Question

Load Image one time with Picasso library

I am using Picasso library to get Image from an url.

My problem is when I load an Image for the first time and I exit out of my app and after I come back my app tries to load the Image again but I don't want it happen. Are there any other way to do that(load just one time the Image and in others time don't need to Internet for load)?

Answer

The issue with the above answers is that they only check the availability of the images in the disk cache, it does not cover the part if the image does not exist in the cache to go online and retrieve it.

First make a class that extends Application (You can name it whatever you want that does not interfere with your application, my convention is to use "Global").

    public class Global extends Application {

        @Override
        public void onCreate() {
            super.onCreate();

            Picasso.Builder builder = new Picasso.Builder(this);
            builder.downloader(new OkHttpDownloader(this,Integer.MAX_VALUE));
            Picasso built = builder.build();
            built.setIndicatorsEnabled(false);
            built.setLoggingEnabled(true);
            Picasso.setSingletonInstance(built);
        } 
}

Make sure you add dependancy for OkHttp library, it's developed by the same guys from Picasso

compile 'com.squareup.okhttp:okhttp:2.4.0'

and add the class in your Manifest file Applications tag :

android:name=".Global"

Then when you want to retrieve the image :

      Picasso.with(context)
             .load(Image URL)
             .networkPolicy(NetworkPolicy.OFFLINE)
             .into(imageView, new Callback() {
              @Override
              public void onSuccess() {
    }

             @Override
             public void onError() {
             //Try again online if cache failed
             Picasso.with(context)
             .load(Image URL)
             .into(imageView, new Callback() {

                @Override
               public void onSuccess() {

               }

               @Override
              public void onError() {
                   Log.v("Picasso","Could not fetch image");
              }
        });
     }
  });

The above method checks if the image is already cached, if not gets it from the internet.

Comments