gpt4 book ai didi

android - 如何在不阻塞的情况下等待 Android UI 线程中异步填充的对象?

转载 作者:行者123 更新时间:2023-11-29 02:33:43 26 4
gpt4 key购买 nike

我有一个单例来处理实体 Profilo(一个配置文件)的注册和消除。

这个实体是通过在服务器上以异步方式传递标识符和收集信息来设置的。

我的问题是,当我必须返回我的 profilo 实例时,如果它尚未加载,它将返回 null。

public class AccountHandler {
private static AccountHandler istanza = null;

Context context;
private boolean logged;
private Profilo profilo;


private AccountHandler(Context context) {
this.context = context;
//initialization
//setting logged properly
assignField(this.getName());
}
}

public static AccountHandler getAccountHandler(Context context) {
if (istanza == null) {
synchronized (AccountHandler.class) {
if (istanza == null) {
istanza = new AccountHandler(context);
}
}
}
return istanza;
}

public void setAccount(String nickname, String accessingCode) {
logged = true;
assignField(nickname);
}

//other methods

private void assignField(String nickname) {
ProfiloClient profiloClient = new ProfiloClient();
profiloClient.addParam(Profilo.FIELDS[0], nickname);
profiloClient.get(new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode,
Header[] headers,
JSONArray response) {
JSONObject objson = null;
try {
objson = (JSONObject) response.getJSONObject(0);
} catch (JSONException e) {
e.printStackTrace();
}
AccountHandler accountHandler = AccountHandler.getAccountHandler(context);
// Profilo is created with a JSONObject
// **setProfilo is called in async**
**accountHandler.setProfilo(new Profilo(objson));**
}

});
}


private void setProfilo(Profilo profilo) {
this.profilo = profilo;
}



public Profilo getProfilo() {
if( logged && profilo == null)
//How can I wait that profilo is loaded by the JsonHttpResponseHandler before to return it

return this.profilo;
}


}

最佳答案

您可以使用回调机制代替调用 getProfilo,其中 AccountHandler 类会在加载配置文件时通知调用者。例如

  public void setAccount(String nickname, String accessingCode, MyCallback cb) {
assignField(nickname, cb);
}
private void assignField(String nickname, MyCallback cb) {
....
accountHandler.setProfilo(new Profilo(objson));
cb.onSuccess(this.profilo);
}

在您的 AccountHandler 类中创建一个内部接口(interface) MyCallback(重命名)

public class AccountHandler {
public interface MyCallback {
void onSuccess(Profilo profile);
}
}

现在,无论何时调用 setAccount,您都会传递回调并在配置文件可用时收到通知,例如

accountHandler.setAccount("Test", "Test", new AccountHandler.MyCallback() {
void onSuccess(Profilio profile) {
// do something with the profile
}
}

关于android - 如何在不阻塞的情况下等待 Android UI 线程中异步填充的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48204508/

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