gpt4 book ai didi

java.lang.IllegalStateException : Method call should not happen from the main thread with piccaso 错误

转载 作者:行者123 更新时间:2023-11-30 01:07:16 37 4
gpt4 key购买 nike

我正在尝试在用户登录时创建一个用户对象并将其保存在共享首选项中。用户对象具有我从 json 对象中检索的姓名和姓氏,以及我试图通过 piccaso 获取的位图配置文件图片(图片的行也在 json 对象中)。我在这两种情况下都尝试了 volley 和 asynctask,我得到了 expeption。

我的用户模型:

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);


}

}

最佳答案

基本上就是对NetworkOnMainThreadException的封装

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

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

它有效地执行远程调用以从 object.getString("image") URL 检索图片。确保调用在非 UI 线程上执行。这是使用 Picasso 的主要优势,因为它确保网络处理和数据缓冲在一个线程内完成,并且在 Android 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
}
});

关于java.lang.IllegalStateException : Method call should not happen from the main thread with piccaso 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38762270/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com