Skip to content

Instantly share code, notes, and snippets.

@hrishikesh-kadam
Last active May 5, 2020 13:15
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hrishikesh-kadam/09cef31c736de088313f1a102f5ed3a3 to your computer and use it in GitHub Desktop.
Save hrishikesh-kadam/09cef31c736de088313f1a102f5ed3a3 to your computer and use it in GitHub Desktop.
Custom Picasso for redirecting image URLs

CustomPicasso

A util class which helps to load redirecting image URLs using Picasso and Jake Wharton's picasso2-okhttp3-downloader.

Singleton approach -

    CustomPicasso.with(context)
        .load("http://i.imgur.com/DvpvklR.png")
        .into(imageView);

Benefit of singleton approach is to avoid memory leak.

Non singleton approach -

    Picasso customPicasso = CustomPicasso.getNewInstance(context);
    customPicasso.load("http://i.imgur.com/DvpvklR.png")
        .into(imageView);

    //After usage call shutdown to avoid memory leak e.g. in onDestroy() of activity
    customPicasso.shutdown();
android {
...
}
dependencies {
...
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'
}
import android.content.Context;
import android.util.Log;
import com.jakewharton.picasso.OkHttp3Downloader;
import com.squareup.picasso.Picasso;
/**
* Created by Hrishikesh Kadam on 19/12/2017
*/
public class CustomPicasso {
private static String LOG_TAG = CustomPicasso.class.getSimpleName();
private static boolean hasCustomPicassoSingletonInstanceSet;
public static Picasso with(Context context) {
if (hasCustomPicassoSingletonInstanceSet)
return Picasso.with(context);
try {
Picasso.setSingletonInstance(null);
} catch (IllegalStateException e) {
Log.w(LOG_TAG, "-> Default singleton instance already present" +
" so CustomPicasso singleton cannot be set. Use CustomPicasso.getNewInstance() now.");
return Picasso.with(context);
}
Picasso picasso = new Picasso.Builder(context).
downloader(new OkHttp3Downloader(context))
.build();
Picasso.setSingletonInstance(picasso);
Log.w(LOG_TAG, "-> CustomPicasso singleton set to Picasso singleton." +
" In case if you need Picasso singleton in future then use Picasso.Builder()");
hasCustomPicassoSingletonInstanceSet = true;
return picasso;
}
public static Picasso getNewInstance(Context context) {
Log.w(LOG_TAG, "-> Do not forget to call customPicasso.shutdown()" +
" to avoid memory leak");
return new Picasso.Builder(context).
downloader(new OkHttp3Downloader(context))
.build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment