Java Reference
In-Depth Information
JsonObject jsonObject = jr.readObject();
JsonArray jsonArray = jsonObject.getJsonArray("items");
ObservableList<Question> answer = FXCollections.observableArrayList();
jsonArray.iterator().forEachRemaining((JsonValue e) -> {
JsonObject obj = (JsonObject) e;
JsonString name = obj.getJsonObject("owner").getJsonString("display_name");
JsonString quest = obj.getJsonString("title");
JsonNumber jsonNumber = obj.getJsonNumber("creation_date");
Question q = new Question(name.getString(), quest.getString(),
jsonNumber.longValue() * 1000);
System.out.println("Adding question "+q);
answer.add(q);
});
return answer;
}
};
}
}
The
QuestionRetrievalService
extends
Service
and thus has to implement a
createTask
method.
When the
Service
is started, this task is executed in a separate
Thread
. The
createTask
method on the
QuestionRetrievalService
creates a new
Task
and returns it. The signature of this method,
Task<ObservableList<Question>>createTask(),
ensures that the
Task
creates an
ObservableList
of questions. The generic type parameter
ObservableList<Question>
is the same as the type parameter in the declaration of the
Service
. As a consequence, the
getValue()
method of the
Service
will also return an
ObservableList
of
Question
s.
Indeed, the following code snippet states that the
questionRetrievalService.getValue()
should return an
ObservableList<Question>.
ObservableList<Question> answer = FXCollections.observableArrayList();
...
if (now == State.SUCCEEDED) {
answer.addAll(service.getValue());
}
The
Task
instance that we created in the
QuestionRetrievalService
has to implement the call method. This
method is actually doing what the
getObservableList
method in the previous examples was doing: retrieving the
data and parsing them.
Although the real work in a
Service
(the
Task
created by
createTask
) is done in a background
Thread
, all
methods on the
Service
, including the
getValue()
call, should be accessed from the JavaFX
Thread
. The internal
implementation makes sure that all changes to the available properties in the
Service
are executed on the JavaFX
application
Thread
.
Running the example gives the exact same visual output as running the previous example. However, we added
some
System.out
messages for clarity. If we run the example, the following messages can be seen on the console.
State of service is READY
State of service is SCHEDULED
Search WWH ::
Custom Search