java.lang.IllegalStateException:方法调用不应该发生在带有piccaso的主线程中

时间:2016-08-04 08:30:50

标签: java android picasso

我试图在用户登录时创建用户对象并将其保存在共享的prefrences中。用户对象具有从json对象中恢复的名称和姓氏以及我试图通过piccaso获取的位图配置文件pic(图片的行也在json对象中)。我用凌空和asynctask尝试了它,在这两种情况下我都得到了它。

我的用户模型:

public class User{

    private String name,lastName;
    private Bitmap profilePicture;
    Context context;

    public User(JSONObject object , Context context){
        this.context = context;

        try {
            this.name = object.getString("firstName");
            this.lastName = object.getString("lastName");
            this.profilePicture = Picasso.with(context).load(object.getString("image")).get();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

和我的截击请求:

  JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {

                            Intent intent = new Intent(LoginActivityScreen.this, HomeActivityScreen.class);

                            SharedPreferences.Editor editor = preferences.edit();

                            RoomateModel model = new RoomateModel(response, context);


                            Gson gson = new Gson();
                            String json = gson.toJson(model);
                            editor.putString("USER", json);
                            editor.commit();


                            startActivity(intent);


                        }

                    }

2 个答案:

答案 0 :(得分:2)

基本上它是NetworkOnMainThreadException的封装。

你需要检查你在哪里调用User(...)构造函数,因为他们有这一行:

this.profilePicture = Picasso.with(context).load(object.getString("image")).get();

远程调用有效地从object.getString("image") URL检索图片。确保在非UI线程上执行调用。这是使用Picasso的主要优点,因为它确保网络处理和数据缓冲在一个线程内完成,并且在UI UI元素(ImageView)内的资源(图像)膨胀是在UI线程上完成的,没有任何来自图书馆用户的额外努力。

或者,您可以尝试使用Picasso的Target界面:

Picasso.with(context).load(object.getString("image").into(new Target() {
    @Override
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
        //This gets called when your application has the requested resource in the bitmap object
        User.this.profilePicture = bitmap;
    }

    @Override
    public void onBitmapFailed(Drawable errorDrawable) {
        //This gets called if the library failed to load the resource
    }

    @Override
    public void onPrepareLoad(Drawable placeHolderDrawable) {
        //This gets called when the request is started
    }
});

答案 1 :(得分:-1)

尝试在代码加载图片之前添加此部分

if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy =
                    new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
}