我正在开发 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/