Use Picasso to get a callback with a Bitmap
Found the answer on github in case anyone is wondering:
private Target target = new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
private void someMethod() {
Picasso.with(this).load("url").into(target);
}
@Override
public void onDestroy() { // could be in onPause or onStop
Picasso.with(this).cancelRequest(target);
super.onDestroy();
}
The post recommends not using an anonymous callback, and instead using an instance variable for target.
taken from here:
Picasso.with(this)
.load(url)
.into(new Target() {
@Override
public void onBitmapLoaded (final Bitmap bitmap, Picasso.LoadedFrom from){
/* Save the bitmap or do something with it here */
//Set it in the ImageView
theView.setImageBitmap(bitmap);
}
});
Updated (May 04, 2016):
Picasso.with(this)
.load(youUrl)
.into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
Updated (November 22, 2016)
or using a strong reference for Target
so that it wont be garbage collected
Target target = new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
void foo() {
Picasso.with(getContext()).load(getUrl()).into(target);
}
Kotlin
object: com.squareup.picasso.Target {
override fun onBitmapFailed(e: java.lang.Exception?, errorDrawable: Drawable?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onPrepareLoad(placeHolderDrawable: Drawable?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) {
}
}
What can be easy than next:
val url: String = "https://...."
val bitmap: Bitmap = Picasso.with(context).load(url).get()
Should be called from not the main thread!
or with RxJava 2:
fun getBitmapSingle(picasso: Picasso, url: String): Single<Bitmap> = Single.create {
try {
if (!it.isDisposed) {
val bitmap: Bitmap = picasso.load(url).get()
it.onSuccess(bitmap)
}
} catch (e: Throwable) {
it.onError(e)
}
}
Retrieve Bitmap:
getBitmapSingle(Picasso.with(context), "https:/...")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ bitmap ->
// val drawable = BitmapDrawable(context, bitmap)
}, Throwable::printStackTrace)
I used Picasso v.2.5.2