ArrayList返回null值

时间:2014-10-25 10:59:57

标签: 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列表为空。希望有人会帮忙。 贾科莫。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

你对异步感到困惑。这是它的工作原理,语言学

  1. 您创建一个空列表
  2. 您发送HTTP请求
  3. 您返回列表
  4. 来电者显示列表的大小:0
  5. 一段时间后,当对请求的响应返回时,调用onResponseReceived()回调方法并将元素添加到列表中。
  6. 该方法不应返回列表,因为它始终为空。相反,一旦您实际收到HTTP响应并填充了列表,就应该从onResponseReceived()方法调用显示列表的代码。