Jake Alsemgeest Jake Alsemgeest -4 years ago 510
Android Question

Android Picasso: Not Loading in Fragment

I am giving Picasso a try for some easier memory management with images. I have just been trying to implement it within my fragment however I can't seem to get it to work.

mainLayout.setBackground(new BitmapDrawable(getResources(), Picasso.with(mainLayout.getContext()).load(R.drawable.background2).get()));

Where mainLayout is a LinearLayout. I also tried this:


I have tried Picasso.with(this)... but this doesn't work at all.

I keep getting an Exception of:

java.lang.IllegalStateException: Method call should not happen from the main thread.
at com.squareup.picasso.Utils.checkNotMain(Utils.java:71)
at com.squareup.picasso.RequestCreator.get(RequestCreator.java:206)
at ...

where I called it.

Anyone experience this or know how to use this properly with fragments?

Answer Source

The exception message states it pretty clear. The .get() message is not async, hence will do the work (network, read file,... whatever) on the main thread, which you should avoid whenever possible.

Your code for setting the image to an imageView seems correct to me, though.

I think it is also possible to do the same with the mainLayout (Picasso will then set the drawable/Bitmap to the background automatically). If I'm wrong here, have a look at the Target.class which comes with Picasso. You could load the image into a target, which must provide handlers for success and error. Within the success handler you will get the bitmap once it is loaded and can set it to your bakground.

There are a few solutions, which might work in your case.


When using the get() Method provided by Picasso the loading will take place in the thread you are currently working in, which is clearly stated in the sources: https://github.com/square/picasso/blob/master/picasso/src/main/java/com/squareup/picasso/RequestCreator.java

/** Synchronously fulfill this request. Must not be called from the main thread. */

public Bitmap get() throws IOException {[...]}

In your case I would use the Target interface, which provides callbacks when the image is loaded.

Picasso.with(getActivity()).load(R.drawable.background2).into(new Target(){

  public void onBitmapLoaded(Bitmap bitmap, LoadedFrom from) {
     mainLayout.setBackground(new BitmapDrawable(context.getResources(), bitmap));

  public void onBitmapFailed(final Drawable errorDrawable) {
      Log.d("TAG", "FAILED");

  public void onPrepareLoad(final Drawable placeHolderDrawable) {
      Log.d("TAG", "Prepare Load");

As you are using an internal resource here, why don't you just do the following?


Hope this helps.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download