Picasso java.lang.IllegalStateException:方法调用不应该从主线程发生

问题描述 投票:15回答:3

我试图用毕加索从Bitmap获得三张URL图像

public void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState);
  setContentView(R.layout.tab2);
  Drawable d1 = new BitmapDrawable(Picasso.with(Tab2.this).load(zestimateImg1).get());
}

我正在使用此代码获取FATAL EXCEPTION。我怀疑它与AsyncTask中应该完成的事实有关,但我无法让它工作。如果使用这是可以避免的,我想这样做而不使用AsyncTask

如何在不崩溃的情况下运行此代码?

如果最好的方法是使用AsyncTask,那么这个解决方案是可以的。

android android-asynctask imageview illegalstateexception picasso
3个回答
9
投票

您无法在主线程中发出同步请求。如果您不想使用AsyncThread,那么只需将Picasso与Target一起使用即可。

Picasso.with(Tab2.this).load(zestimateImg1).into(new Target(...);

我建议您保存对目标的引用,如下所示:

Target mTarget =new Target (...); 

这是因为Picasso对它们使用弱引用,并且它们可能在进程完成之前被垃圾收集。


8
投票

以上都不适用于我而不是这个

Handler uiHandler = new Handler(Looper.getMainLooper());
    uiHandler.post(new Runnable(){
        @Override
        public void run() {
            Picasso.with(Context)
                    .load(imageUrl)
                    .into(imageView);
        }
    });

希望它对某些人有用


3
投票

仅供记录:

Picasso.with(context).load(url).into(new Target() {
    @Override
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
        Log.i(TAG, "The image was obtained correctly");
    }

    @Override
    public void onBitmapFailed(Drawable errorDrawable) {
        Log.e(TAG, "The image was not obtained");
    }

    @Override
    public void onPrepareLoad(Drawable placeHolderDrawable) {
        Log.(TAG, "Getting ready to get the image");
        //Here you should place a loading gif in the ImageView
        //while image is being obtained.
    }
});

资料来源:http://square.github.io/picasso/

在启动请求后始终调用onPrepareLoad()from可以是“DISK”,“MEMORY”或“NETWORK”来指示从中获取图像的位置。

© www.soinside.com 2019 - 2024. All rights reserved.