I’m coding a servlet in GWT and I don’t really understand what’s happening with the data variable declared as global in the function. Maybe it’s a more general Java issue related with using variables into dynamic function declarations but I can’t find an answer to this.
This is my code:
private AbstractDataTable fetchDataFromServer() {
final DataTable data = DataTable.create();
System.out.println("1 Table has " + data.getNumberOfColumns() + " columns");
System.out.println("1 Table has " + data.getNumberOfRows() + " rows");
try {
RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, "/mongo.json");
rb.setCallback(new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
JSONValue value = JSONParser.parse(response.getText());
JSONObject productsObj = value.isObject();
JSONArray radiation = productsObj.get("ShortWave_Rad").isArray();
if (radiation != null) {
data.addColumn(ColumnType.NUMBER, "Horizon");
data.addColumn(ColumnType.NUMBER, "Value");
System.out.println("Values " + radiation.size());
for (int i=0; i<=radiation.size()-1; i++) {
JSONObject productObj = radiation.get(i).isObject();
data.addRows(radiation.size());
data.setValue(i, 0, productObj.get("horizon").isNumber().doubleValue());
data.setValue(i, 1, productObj.get("value").isNumber().doubleValue());
}
System.out.println("2 Table has " + data.getNumberOfColumns() + " columns");
System.out.println("2 Table has " + data.getNumberOfRows() + " rows");
}
}
@Override
public void onError(Request request, Throwable exception) {
Window.alert("Error occurred" + exception.getMessage());
}
});
rb.send();
}
catch (RequestException e) {
Window.alert("Error occurred" + e.getMessage());
}
System.out.println("3 Table has " + data.getNumberOfColumns() + " columns");
System.out.println("3 Table has " + data.getNumberOfRows() + " rows");
return data;
}
And this is the output I get:
1 Table has 0 colums
1 Table has 0 rows
2 Table has 2 colums
2 Table has 10 rows
3 Table has 0 colums
3 Table has 0 rows
Where did the contents of data went after the onResponseReceived declaration used it?
Many thanks for your help.
Your
onResponseReceivedis invoked after a asynchronous call response. It is very much likely that statements below are executed before it receives the response.Use some status flag to to check the status of call back before printing the size in the end.