0

I want to add basic authorization in Picasso library instance to download images.

Please let me know if you are able to find any bug/suggestion.

Source code:

public class MyPicasso {

private static MyPicasso mInstance;
private static Picasso picasso;
private static Context ctx;

public static synchronized MyPicasso getInstance(Context context) {
    ctx = context;
    if (mInstance == null) {
        mInstance = new MyPicasso();
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .authenticator(new Authenticator() {
                    @Override
                    public Request authenticate(Route route, Response response) throws IOException {
                        String credential = Credentials.basic(Constants.BASIC_AUTH_USERNAME, Constants.BAISC_AUTH_PASSWORD);
                        return response.request().newBuilder()
                                .header("Authorization", credential)
                                .build();
                    }
                })
                .build();



        Picasso.Builder builder = new Picasso.Builder(context);
        OkHttp3Downloader downloader = new OkHttp3Downloader(okHttpClient);
        picasso = builder.downloader(downloader).build();
    }
    return mInstance;
}

public synchronized void downloadImage(String url, ImageView imageView) {
    if (picasso == null) throw new ExceptionInInitializerError("Picasso Initializer Error");

    downloadImage(url, imageView, null);
}

public synchronized void downloadImage(String url, ImageView imageView, Drawable userPlaceholder) {
    if (picasso == null) throw new ExceptionInInitializerError("Picasso Initializer Error");

    Drawable productPlaceholder = ContextCompat.getDrawable(ctx, R.mipmap.ic_launcher);

    picasso.with(ctx).load(url)
            .into(imageView);
}

Using like this
MyPicasso.getInstance("application context here").downloadImage("image_url_here","Imageview_here");

///May be helpful for someone so posting what i did to make it working after research. Not sure what was wrong, but its working perfect now

I updated this code snippet

Picasso.Builder builder = new Picasso.Builder(context);
  picasso = builder.downloader(new OkHttp3Downloader(okHttpClient)).build();

instead of

Picasso.Builder builder = new Picasso.Builder(context);
        OkHttp3Downloader downloader = new OkHttp3Downloader(okHttpClient);
        picasso = builder.downloader(downloader).build();

so it worked for me.

kulvinder
  • 529
  • 5
  • 17

0 Answers0