java - ArrayList 返回空值

标签 java android json arraylist singleton

我正在开发 Java 应用程序。 我创建了一个 Singleton 类来将该类的实例化限制为一个对象。 在同一个类中,我有一个方法返回名为 GuestAgent 的对象的 ArrayList。 这是我的方法:

//Singleton class: Tenant
public ArrayList<GuestAgent> gAgentList() {
    final ArrayList<GuestAgent> guestAgents = new ArrayList<>();
    String url = "http://localhost:8080/StackUI/v2.0/";
    url = url + this.tenantId;
    url = url + "/os-agents";

    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
    builder.setHeader("X-Auth-Token", this.tokenId);

    try {
        builder.sendRequest(null, new RequestCallback() {
            @Override
            public void onError(Request request, Throwable exception) {
                Window.alert("Attenzione si è verificato un errore");
            }

            @Override
            public void onResponseReceived(Request request, Response response) {
                if (200 == response.getStatusCode()) {
                    final HTML respBox = new HTML();
                    respBox.setHTML(response.getText());

                    String risposta = response.getText();

                    JSONValue jsonValue;
                    JSONArray jsonArray;
                    JSONObject jsonObject;
                    JSONString jsonString;
                    JSONNumber jsonNumber;

                    jsonValue = JSONParser.parseStrict(risposta);

                    if ((jsonObject = jsonValue.isObject()) == null) {
                        Window.alert("Error parsing the JSON");
                    }

                    jsonValue = jsonObject.get("agents");
                    if ((jsonArray = jsonValue.isArray()) == null) {
                        Window.alert("Error parsing the JSON");
                    }

                    for (int i = 0; i < jsonArray.size(); i++) {
                        GuestAgent guestAgent = new GuestAgent();
                        jsonValue = jsonArray.get(i);

                        if ((jsonObject = jsonValue.isObject()) == null) {
                            Window.alert("Error parsing the JSON");
                        }

                        jsonValue = jsonObject.get("agent_id");
                        if ((jsonNumber = jsonValue.isNumber()) == null) {
                            Window.alert("Error parsing the JSON");
                        }
                        guestAgent.setAgentId(jsonNumber.toString());

                        jsonValue = jsonObject.get("architecture");
                        if ((jsonString = jsonValue.isString()) == null) {
                            Window.alert("Error parsing the JSON");
                        }
                        guestAgent.setArchitecture(jsonString.stringValue());

                        jsonValue = jsonObject.get("hypervisor");
                        if ((jsonString = jsonValue.isString()) == null) {
                            Window.alert("Error parsing the JSON");
                        }
                        guestAgent.setHypervisor(jsonString.stringValue());

                        jsonValue = jsonObject.get("md5hash");
                        if ((jsonString = jsonValue.isString()) == null) {
                            Window.alert("Error parsing the JSON");
                        }
                        guestAgent.setMd5hash(jsonString.stringValue());

                        jsonValue = jsonObject.get("os");
                        if ((jsonString = jsonValue.isString()) == null) {
                            Window.alert("Error parsing the JSON");
                        }
                        guestAgent.setOs(jsonString.stringValue());

                        jsonValue = jsonObject.get("url");
                        if ((jsonString = jsonValue.isString()) == null) {
                            Window.alert("Error parsing the JSON");
                        }
                        guestAgent.setUrl(jsonString.stringValue());

                        jsonValue = jsonObject.get("version");
                        if ((jsonString = jsonValue.isString()) == null) {
                            Window.alert("Error parsing the JSON");
                        }
                        guestAgent.setVersion(jsonString.stringValue());

                        guestAgents.add(guestAgent);
                    }

                } else {
                    // Handle the error.  Can get the status text from response.getStatusText()
                    Window.alert("Errore " + response.getStatusCode() + " " + response.getStatusText());
                }
            }
        });
    } catch (RequestException e) {
        // Couldn't connect to server   
        Window.alert("Impossibile connettersi al server");
    }

    return guestAgents;
}

从其他类激活方法:

//Other class
ArrayList<GuestAgent> agents;
agents = Tenant.getTenantObject().gAgentList();
Window.alert(Integer.toString(agents.size()));

此时,我发现agents列表为空。希望有人能帮忙。 贾科莫。

最佳答案

RequestBuilder 进行的调用是异步的,这意味着在调用 builder.sendRequest 后,需要一些时间来运行两个回调方法之一 onError onResponseReceived

您的问题是您正确启动了异步进程,但您立即返回 guestAgents 数组! (查看代码的最后一行)。此时异步调用的结果尚未准备好,数组仍为空。

这样的方法通常不提供返回值,但它们采用回调函数作为参数,该函数将在进程完成时调用,并包含结果值。换句话说,您始终需要等待请求完全完成才能访问 guestAgents 数组。

我会这样做(我用一个简单的记事本做的,没有编译,可能会有错误......):

//Other class
ArrayList<GuestAgent> agents;
agents = Tenant.getTenantObject().gAgentList(new AgentsResultCallback {
    void onCompleted(ArrayList<GuestAgent> agents) {
        // here we have the result!
        if (agents != null) { // check for errors 
            Window.alert(Integer.toString(agents.size()));
        }
    }
});

单例:

//Singleton class: Tenant   (LOOK AT THE VOID RETURN VALUE!)
public void gAgentList(final AgentsResultCallback callback) {
    final ArrayList<GuestAgent> guestAgents = new ArrayList<>();
    String url = "http://localhost:8080/StackUI/v2.0/";
    url = url + this.tenantId;
    url = url + "/os-agents";

    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
    builder.setHeader("X-Auth-Token", this.tokenId);

    try {
        builder.sendRequest(null, new RequestCallback() {
            @Override
            public void onError(Request request, Throwable exception) {
                Window.alert("Attensione si è verificato un errore");
                callback.onCompleted(null); // call the callback with null results 
            }

            @Override
            public void onResponseReceived(Request request, Response response) {
                if (200 == response.getStatusCode()) {
                    final HTML respBox = new HTML();
                    respBox.setHTML(response.getText());

                    String risposta = response.getText();

                    JSONValue jsonValue;
                    JSONArray jsonArray;
                    JSONObject jsonObject;
                    JSONString jsonString;
                    JSONNumber jsonNumber;

                    jsonValue = JSONParser.parseStrict(risposta);

                    if ((jsonObject = jsonValue.isObject()) == null) {
                        Window.alert("Error parsing the JSON");
                    }

                    jsonValue = jsonObject.get("agents");
                    if ((jsonArray = jsonValue.isArray()) == null) {
                        Window.alert("Error parsing the JSON");
                    }

                    for (int i = 0; i < jsonArray.size(); i++) {
                        GuestAgent guestAgent = new GuestAgent();
                        jsonValue = jsonArray.get(i);

                        if ((jsonObject = jsonValue.isObject()) == null) {
                            Window.alert("Error parsing the JSON");
                        }

                        jsonValue = jsonObject.get("agent_id");
                        if ((jsonNumber = jsonValue.isNumber()) == null) {
                            Window.alert("Error parsing the JSON");
                        }
                        guestAgent.setAgentId(jsonNumber.toString());

                        jsonValue = jsonObject.get("architecture");
                        if ((jsonString = jsonValue.isString()) == null) {
                            Window.alert("Error parsing the JSON");
                        }
                        guestAgent.setArchitecture(jsonString.stringValue());

                        jsonValue = jsonObject.get("hypervisor");
                        if ((jsonString = jsonValue.isString()) == null) {
                            Window.alert("Error parsing the JSON");
                        }
                        guestAgent.setHypervisor(jsonString.stringValue());

                        jsonValue = jsonObject.get("md5hash");
                        if ((jsonString = jsonValue.isString()) == null) {
                            Window.alert("Error parsing the JSON");
                        }
                        guestAgent.setMd5hash(jsonString.stringValue());

                        jsonValue = jsonObject.get("os");
                        if ((jsonString = jsonValue.isString()) == null) {
                            Window.alert("Error parsing the JSON");
                        }
                        guestAgent.setOs(jsonString.stringValue());

                        jsonValue = jsonObject.get("url");
                        if ((jsonString = jsonValue.isString()) == null) {
                            Window.alert("Error parsing the JSON");
                        }
                        guestAgent.setUrl(jsonString.stringValue());

                        jsonValue = jsonObject.get("version");
                        if ((jsonString = jsonValue.isString()) == null) {
                            Window.alert("Error parsing the JSON");
                        }
                        guestAgent.setVersion(jsonString.stringValue());

                        guestAgents.add(guestAgent);


                    }

                        // FINISHED! results are complete so I send them to the callback
                        callback.onCompleted(guestAgents);

                } else {
                    // Handle the error.  Can get the status text from response.getStatusText()
                    Window.alert("Errore " + response.getStatusCode() + " " + response.getStatusText());
                    callback.onCompleted(null); // call the callback with null results here, too
                }
            }
        });
    } catch (RequestException e) {
        // Couldn't connect to server   
        Window.alert("Impossibile connettersi al server");
    }

    return; // return nothing!
}

以及回调类的小声明:

abstract public class AgentsResultCallback {
    abstract void onCompleted(ArrayList<GuestAgent> agents);
}

关于java - ArrayList 返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26561645/

相关文章:

java - 为什么 Eclipse 提示类型转换不安全?

java - repaint() JFrame 和 JPanel

javascript - Jquery从php/json文件加载数据并将新内容附加到div以进行聊天

java - 无法预实例化名为 org.sakaiproject.accountvalidator.dao.impl.ValidationLogicDaoTarget 的单例

java - 获得超过 100% 的 Smith-Waterman 计算

打开数据库时,Android sqlite 数据库 setlocale 太慢。怎么解决?

javascript - 无法让我的变量将其值保留在 getJSON 之外

windows - < 这时候出乎意料。在将输入数据作为 xml 发布到休息服务时从 curl 命令行

android - 是什么让 Google Maps/Youtube 能够显示 'Complete this action with' 菜单?

javascript - 如何创建在 React-Native 中检测自动位置的 map