我正在研究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之后,需要花费一些时间来运行两个回调方法onErroronResponseReceived之一。

您的问题是您正确启动了异步过程,但是您将立即返回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/

10-12 00:28
查看更多