Jake Alsemgeest Jake Alsemgeest - 3 months ago 30
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:

Picasso.with(getActivity().getApplicationContext()).load(R.drawable.background2).into(imageView1);


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

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.

[EDIT]

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(){

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

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

  @Override
  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?

mainLayout.setBackgroundResource(R.drawable.background2);

Hope this helps.

Regards