I have the following implementation of the call method
of the class SaveData
that extends the Task
class in JavaFX
:
@Override
protected Void call() {
try {
SheetWriter publicationWriter = new SheetWriter(destinationPath);
publicationWriter.write(publicationHeaders);
if (savingOption.equals("excel")) {
for (JSONArray jsonArray : searchResult) {
for (int i = 0; i < jsonArray.length(); i++) {
Publication currentPublication = new Publication(jsonArray.getJSONObject(i));
publicationWriter.write(currentPublication.getSCVData());
}
}
}
publicationWriter.close();
} catch (IOException e) {
System.out.println(e.getMessage());
throw new RuntimeException("Exception occurred");
}
return null;
}
The idea is to loop through a list of JSONArrays
where each contains JSONObjects
, and save them into a CSV file using CSVWriter
of openCSV
.
This is SheetWriter
class:
public class SheetWriter {
FileWriter fileWriter;
CSVWriter csvWriter;
public SheetWriter(String fileName) throws IOException {
fileWriter = new FileWriter(fileName);
csvWriter = new CSVWriter(fileWriter);
}
public void write(String[] inputArray) {
csvWriter.writeNext(inputArray);
}
public void close() throws IOException {
// fileWriter.close();
csvWriter.close();
}
}
The action is triggered when the user clicks the save button. This is the code that handles the action when triggered:
saveButton.setOnAction(event -> new Thread(() -> {
Platform.runLater(() -> saveButton.setDisable(true));
SaveData saveDataTask = new SaveData("C:\Users\PC\IdeaProjects\NewsPaperScrapper\src\result\data.csv", result);
if (currentOption.equals("excel"))
saveDataTask.setSavingOption("excel");
else
saveDataTask.setSavingOption("json");
saveDataTask.setOnSucceeded(e -> {
System.out.println("Saved!!");
Platform.runLater(() -> saveButton.setDisable(false));
});
new Thread(saveDataTask).start();
}).start());
The issue is that setOnSucceeded
is invoked immediately and does not wait for the task to complete and save the CSV file.
I would like to know what is causing the issue. knowing that I have tried changing the return type of the task to boolean, and also running the task on the same thread using the run method