TableView not showing any value Javafx 8 [duplicate] - java

This question already has answers here:
Javafx tableview not showing data in all columns
(3 answers)
Closed 1 year ago.
im working on a project and i need to populate a TableView with data from a database. in this same project i've worked with other TableView and i had no problem so far. but i already tried a lot of stuff, checked the solution to this: Javafx tableview not showing data in all columns and didnt work either, i already dont know what to do, hope you can help me, ill show you the code:
TableView column fill:
private void fillColumns(){
TableColumn<Exam, String> column1 = new TableColumn<>("Estudio");
column1.setCellValueFactory(new PropertyValueFactory<>("estudio"));
TableColumn<Exam, String> column2 = new TableColumn<>("Doctor");
column2.setCellValueFactory(new PropertyValueFactory<>("doctor"));
TableColumn<Exam, String> column3 = new TableColumn<>("Fecha");
column3.setCellValueFactory(new PropertyValueFactory<>("fecha"));
TableColumn<Exam, String> column4 = new TableColumn<>("Descripcion");
column4.setCellValueFactory(new PropertyValueFactory<>("descripcion"));
TableColumn<Exam, String> column5 = new TableColumn<>("Precio");
column5.setCellValueFactory(new PropertyValueFactory<>("precio"));
TableColumn<Exam, String> column6 = new TableColumn<>("Paciente");
column6.setCellValueFactory(new PropertyValueFactory<>("paciente"));
//add columns
tvExam.getColumns().clear();
tvExam.getColumns().add(column1);
tvExam.getColumns().add(column2);
tvExam.getColumns().add(column3);
tvExam.getColumns().add(column4);
tvExam.getColumns().add(column5);
tvExam.getColumns().add(column6);
column1.prefWidthProperty().bind(tvExam.widthProperty().multiply(0.2));
column2.prefWidthProperty().bind(tvExam.widthProperty().multiply(0.3));
column3.prefWidthProperty().bind(tvExam.widthProperty().multiply(0.1));
column4.prefWidthProperty().bind(tvExam.widthProperty().multiply(0.2));
column5.prefWidthProperty().bind(tvExam.widthProperty().multiply(0.1));
column6.prefWidthProperty().bind(tvExam.widthProperty().multiply(0.1));
}
My Exam Class:
public class Exam {
protected SimpleStringProperty estudio = null;
protected SimpleStringProperty doctor = null;
protected SimpleStringProperty fecha = null;
protected SimpleStringProperty descripcion = null;
protected SimpleFloatProperty precio;
protected SimpleStringProperty paciente = null;
public Exam() {
}
public Exam(String estudio, String doctor, String fecha, String descripcion, float precio, String paciente){
this.estudio = new SimpleStringProperty(estudio);
this.descripcion = new SimpleStringProperty(descripcion);
this.doctor = new SimpleStringProperty(doctor);
this.fecha = new SimpleStringProperty(fecha);
this.precio = new SimpleFloatProperty(precio);
this.paciente = new SimpleStringProperty(paciente);
}
public String getpaciente() {
return paciente.get();
}
public void setpaciente(String paciente) {
this.paciente = new SimpleStringProperty(paciente);
}
public String getestudio() {
return estudio.get();
}
public void setestudio(String estudio) {
this.estudio = new SimpleStringProperty(estudio);
}
public String getdoctor() {
return doctor.get();
}
public void setdoctor(String doctor) {
this.doctor = new SimpleStringProperty(doctor);
}
public String getfecha() {
return fecha.get();
}
public void setfecha(String fecha) {
this.fecha = new SimpleStringProperty(fecha);
}
public String getdescripcion() {
return descripcion.get();
}
public void setdescripcion(String descripcion) {
this.descripcion = new SimpleStringProperty(descripcion);
}
public float getprecio() {
return precio.get();
}
public void setprecio(float precio) {
this.precio = new SimpleFloatProperty(precio);
}
}
my filling function with data from database (i already checked and the data is there, the problem is the tableview):
while (resultSet.next()) {
Exam nuevo = new Exam();
nuevo.setdoctor(resultSet.getString("fecha"));
nuevo.setestudio(resultSet.getString("estudio"));
nuevo.setpaciente(resultSet.getString("paciente"));
nuevo.setdescripcion(resultSet.getString("descripcion"));
nuevo.setfecha(resultSet.getString("fecha"));
nuevo.setprecio(resultSet.getFloat("precio"));
tvExam.getItems().add(fila);
}

Rename the getters and setters using camelCase.
This is a java standard:
public String getFoo()
{
return this.foo;
}
public void setFoo(String foo)
{
this.foo = foo;
}

Related

Elasticsearch improve search accuracy on Boolean query match, matchesNot, matchesPartial

Need a help about the implementation of how to improve the search accuracy of the elasticSearch logic on the JAVA side which is in the springboot application.
Why I am aiming for search accuracy? Because in the production side whenever I am searching for products using the search bar in the app ex. Laptops it shows different results of product also.
First I have a **controller class ** where the request goes to this endpoint:
#PostMapping("/bsl/view/products/sort-filter")
public Response<SearchByFilterByResponse> viewSortByFilterBy(#RequestBody SearchByDto searchBy) throws IOException{
return Response.success(elasticSearchProductBslService.viewSortByFilterBy(searchBy));
}
RequestBody contains the SearchByDto class where inside of that class I have the filterBy object, where inside of it the structure of query is there.
SearchByDto class:
SearchByDto class
FilterBy class:
private Map<String, List<String>> filter;
private List<KeyValue<String, String>> matches;
private List<KeyValue<String, String>> matchesPartial;
private List<KeyValue<String, String>> matchesNot;
private List<KeyValue<String, RangeValue>> ranges;
private List<String> discludeFieldNotNullAndEmpty;
public List<String> getDiscludeFieldNotNullAndEmpty() {
if(discludeFieldNotNullAndEmpty==null) {
this.discludeFieldNotNullAndEmpty = new ArrayList<>();
}
return discludeFieldNotNullAndEmpty;
}
public void setDiscludeFieldNotNullAndEmpty(List<String> discludeFieldNotNullAndEmpty) {
this.discludeFieldNotNullAndEmpty = discludeFieldNotNullAndEmpty;
}
public List<KeyValue<String, RangeValue>> getRanges() {
if(ranges==null) {
this.ranges = new ArrayList<>();
}
return ranges;
}
public void setRanges(List<KeyValue<String, RangeValue>> ranges) {
this.ranges = ranges;
}
public Map<String, List<String>> getFilter() {
if(filter==null) {
this.filter = new HashMap<>();
}
return filter;
}
public void setFilter(Map<String, List<String>> filter) {
this.filter = filter;
}
public List<KeyValue<String, String>> getMatches() {
if(matches==null) {
this.matches = new ArrayList<>();
}
return matches;
}
public void setMatches(List<KeyValue<String, String>> matches) {
this.matches = matches;
}
public List<KeyValue<String, String>> getMatchesPartial() {
if(matchesPartial==null) {
this.matchesPartial = new ArrayList<>();
}
return matchesPartial;
}
public void setMatchesPartial(List<KeyValue<String, String>> matchesPartial) {
this.matchesPartial = matchesPartial;
}
public List<KeyValue<String, String>> getMatchesNot() {
if(matchesNot==null) {
this.matchesNot = new ArrayList<>();
}
return matchesNot;
}
public void setMatchesNot(List<KeyValue<String, String>> matchesNot) {
this.matchesNot = matchesNot;
}
}
As based on the structure of the code the matches, matchesPartial, matchesNot is nested under the filter Map, and each keyword queries should have key and value.
Now let's go back to the controller class, as you can see inside of the Response.success method
it is calling also the elasticSearchProductBslService.viewSortByFilterBy(searchBy) where inside of the searchBy it contains the request including the filterBy.
Let's jump to the viewSortByFilterBy() method inside of the elasticSearchProductBslService class.
public SearchByFilterByResponse viewSortByFilterBy(SearchByDto searchBy) throws IOException{
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
SearchRequest request = new SearchRequest();
request.indices("product_bsl");
request.source(sourceBuilder);
int fromIndex = searchBy.getPagination().getFrom();
int size = searchBy.getPagination().getSize();
elasticSearchHelper.buildFieldSort(searchBy, sourceBuilder);
sourceBuilder.from(fromIndex);
sourceBuilder.size(size);
BoolQueryBuilder queryBuilder = elasticSearchHelper.boolQueryBuilder(searchBy);
sourceBuilder.query(queryBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHit[] searchHits = response.getHits().getHits();
SearchByFilterByResponse resp = new SearchByFilterByResponse();
resp.setTotalHits(response.getHits().getTotalHits().value);
List<ProductWithImage> products = searchHitToDto(searchHits);
resp.setProducts(products);
return resp;
}
Additional information for you, this is the DTO class for "product_bsl" index. As I will show it to you how it look like in the OpenAPI later.
ProductBslElasticDto class:
public class ProductBslElasticDto {
private String id;
private String name;
private List<OfferElasticDto> offers;
private List<ProductBslElasticCategory> productBslElasticCategory;
private String brandId;
private String brandName;
private String shortdesc;
private String longDesc;
private int brandRating;
private long dateInserted;
private List<String> imagePath;
private String isActive;
private List<String> images;
private List<String> imageId;
private long totalVisits;
private long totalVisitUpdateTime;
private long totalViewCount;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getShortdesc() {
return shortdesc;
}
public void setShortdesc(String shortdesc) {
this.shortdesc = shortdesc;
}
public String getLongDesc() {
return longDesc;
}
public void setLongDesc(String longDesc) {
this.longDesc = longDesc;
}
public int getBrandRating() {
return brandRating;
}
public void setBrandRating(int brandRating) {
this.brandRating = brandRating;
}
public String getBrandId() {
return brandId;
}
public void setBrandId(String brandId) {
this.brandId = brandId;
}
public long getDateInserted() {
return dateInserted;
}
public void setDateInserted(long dateInserted) {
this.dateInserted = dateInserted;
}
public List<ProductBslElasticCategory> getProductBslElasticCategory() {
return productBslElasticCategory;
}
public void setProductBslElasticCategory(List<ProductBslElasticCategory> productBslElasticCategory) {
this.productBslElasticCategory = productBslElasticCategory;
}
public long getTotalVisits() {
return totalVisits;
}
public void setTotalVisits(long totalVisits) {
this.totalVisits = totalVisits;
}
public long getTotalVisitUpdateTime() {
return totalVisitUpdateTime;
}
public void setTotalVisitUpdateTime(long totalVisitUpdateTime) {
this.totalVisitUpdateTime = totalVisitUpdateTime;
}
public String getIsActive() {
return isActive;
}
public void setIsActive(String isActive) {
this.isActive = isActive;
}
public List<String> getImages() {
return images;
}
public void setImages(List<String> images) {
this.images = images;
}
public List<String> getImageId() {
return imageId;
}
public void setImageId(List<String> imageId) {
this.imageId = imageId;
}
public List<OfferElasticDto> getOffers() {
return offers;
}
public void setOffers(List<OfferElasticDto> offers) {
this.offers = offers;
}
public long getTotalViewCount() {
return totalViewCount;
}
public void setTotalViewCount(long totalViewCount) {
this.totalViewCount = totalViewCount;
}
public List<String> getImagePath() {
return imagePath;
}
public void setImagePath(List<String> imagePath) {
sortIndexedImagePaths(imagePath);
this.imagePath = imagePath;
}
private void sortIndexedImagePaths(List<String> imagePaths) {
if (null == imagePaths) return;
for (String path : imagePaths) {
if (null == path ||
!PRODUCT_INDEXED_IMAGE_PATH_PATTERN.matcher(path).find()) {
return;
}
}
imagePaths.sort(String::compareTo);
}
}
Now after I show the DTO you can look back to the viewSortByFilterBy() again. I think you can disregard the SourceBuilder and SearchRequest let's focus on the elasticSearchHelper.boolQueryBuilder(searchBy) as we will jump inside of it.
ElasticSearchHelper class:
#Service
public class ElasticSearchHelper {
private static final String KEY_NAME = "name";
private static final String REGEX_SPACE = " ";
private static final String REGEX_WILDCARD = "*";
public BoolQueryBuilder boolQueryBuilder(SearchByDto searchBy) {
FilterBy filterBy = searchBy.getFilterBy();
BoolQueryBuilder rootBuilder = QueryBuilders.boolQuery();
if(filterBy!=null) {
nestedTermsQueryBuilder(rootBuilder, filterBy.getFilter());
nestedBoolQueryBuilder(rootBuilder, filterBy.getMatches(), MUST);
nestedBoolQueryBuilder(rootBuilder, filterBy.getMatchesNot(), MUST_NOT);
nestedBoolQueryBuilder(rootBuilder, filterBy.getMatchesPartial(), SHOULD);
nestedExistsQueryBuilder(rootBuilder, filterBy.getDiscludeFieldNotNullAndEmpty());
nestedRangeQueryBuilder(rootBuilder, filterBy.getRanges());
}
return rootBuilder;
}
private void nestedTermsQueryBuilder(BoolQueryBuilder rootBuilder, Map<String, List<String>> filter) {
filter.forEach((key, value) -> {
TermsQueryBuilder nestedBuilder = QueryBuilders.termsQuery(key, value);
rootBuilder.must(nestedBuilder);
});
}
private void nestedBoolQueryBuilder(BoolQueryBuilder rootBuilder, List<KeyValue<String, String>> entries, ElasticSearchBoolQueryType queryType) {
if(entries != null && !entries.isEmpty()) {
Set<String> distinctKeys = entries.stream().map(KeyValue::getKey).collect(Collectors.toSet());
for (String key : distinctKeys) {
BoolQueryBuilder nestedBuilder = QueryBuilders.boolQuery();
for (KeyValue<String, String> entry : entries) {
nestedQueryStringOrDisMaxQueryBuilder(key, entry, nestedBuilder);
}
switch (queryType) {
case MUST:
rootBuilder.must(nestedBuilder);
break;
case MUST_NOT:
rootBuilder.mustNot(nestedBuilder);
break;
case SHOULD:
rootBuilder.should(nestedBuilder);
break;
default:
break;
}
}
}
}
I just included the boolQueryBuilder and nestedBoolQueryBuilder only just to focus relating to my concern. don't get confuse on the MUST, MUST_NOT, SHOULD it is the same for matches, matchesNot, matchesPartial as I have told earlier on the FilterBy class. So in this class I think the logic happens here, any suggestions for any changes and how should I improve search accuracy for this kind of structure?
How it looks like in OpenAPI as I will search for product name:
Request: POST "/bsl/view/products/sort-filter"
{
"pagination": {
"from": 0,
"size": 20
},
"sortBy": {
"fieldsAscOrDesc": {
"offers.financing.finalAmount": "desc"
}
},
"filterBy": {
"matches": [
{
"key": "name",
"value": "Lenovo IdeaPad3 81Y4001NPH"
}
],
"matchesNot": [
{
"key": "isActive",
"value": "false"
}
],
"discludeFieldNotNullAndEmpty": [
"offers"
]
}
}
Result was it had total of 17 hits and I used the matches keyword where it should be search the exact word right? But it shows different Lenovo products in the result.
Result

How do I use json to create a custom object?

Real title: How do I convert json to custom object using gson(custom object contains ArrayLists and HashMap)?
Problem:
I added an HashMap to my custom object and since then when im trying to convert JSON to my custom object I get this error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 59 path $[0].currentLesson.students.
What do I need to change? ask for any other info you might need from me and I shall give it to you. Thank you!
Code:
private void initializeDatabase() {
ArrayList<Group> groups = null;
SharedPreferences sharedPreferences = getSharedPreferences(Database.SHARED_PREFERENCES_STRING, MODE_PRIVATE);
Gson gson = new Gson();
String groupsJason = sharedPreferences.getString(Database.GROUPS_STRING, null);
Type typeGroup = new TypeToken<ArrayList<Group>>(){}.getType();
groups = gson.fromJson(groupsJason, typeGroup);
if(groups == null){
groups = new ArrayList<>();
}
Database.setGroups(groups);
}
public class Group {
private String groupName;
private ArrayList<Student> students;
private ArrayList<Lesson> lessons;
private Lesson currentLesson;
public Group(String groupName) {
this.groupName = groupName;
students = new ArrayList<>();
lessons = new ArrayList<>();
}
public Group(String groupName, ArrayList<Student> students) {
this.groupName = groupName;
this.students = students;
lessons = new ArrayList<>();
}
public void setCurrentLesson(String currentLesson) {
this.currentLesson = new Lesson(currentLesson, students);
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public ArrayList<Student> getStudents() {
return students;
}
public int getGroupSize() {
return students.size();
}
public Boolean getArrivedToLesson(Student student){
return currentLesson.getArrivedToLesson(student);
}
public Lesson getCurrentLesson() {
return currentLesson;
}
public void saveLesson() {
lessons.add(currentLesson);
}
}
public class Lesson {
private String lessonDate;
private HashMap<Student, Boolean> students;
public Lesson(String lessonDate, ArrayList<Student> students) {
this.lessonDate = lessonDate;
this.students = new HashMap<>();
for (Student student : students) {
this.students.put(student, false);
}
}
public String getLessonDate() {
return lessonDate;
}
public void arrivedToLesson(Student student) {
student.arrivedToLesson();
students.put(student, true);
}
public void didntArriveToLesson(Student student) {
student.didntArriveToLesson();
students.put(student, false);
}
public Boolean getArrivedToLesson(Student student) {
return students.get(student);
}
}
private void saveData(){
group.saveLesson();
SharedPreferences sharedPreferences = getSharedPreferences(Database.SHARED_PREFERENCES_STRING, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String groupsJason = gson.toJson(Database.getGroups());
editor.putString(Database.GROUPS_STRING, groupsJason);
editor.apply();
Toast.makeText(this, String.format(getResources().getString(R.string.saved_attendance), lessonDate), Toast.LENGTH_SHORT).show();
onButtonBackClick();
}
I've managed to solve the problem. The problem was that my map - I changed it to HashMap<String, Object>. The string represents my custom object's main attribute - in my case it's name, the object is a boolean and I casts it when needed.

Android Studio - Issue loading JSON

I'm using Android Studio and I want to make a listview, which contains values that are received by JSON.
protected Void doInBackground(Void... voids) {
HttpHandler Handler = new HttpHandler();
String JSONString = Handler.makeServiceCall(JSONUrl);
Log.e(TAG, "Response:" + JSONString);
if(JSONString != null){
try {
JSONObject CountriesJSONObject = new JSONObject(JSONString);
JSONArray Countries = CountriesJSONObject.getJSONArray("countries");
for (int i = 1; i < Countries.length(); i++) {
JSONObject Country = Countries.getJSONObject(i);
//Details
String CountryID = Country.getString("id");
String CountryName = Country.getString("name");
String CountryImage = Country.getString("image");
//Hashmap
HashMap<String, String> TempCountry = new HashMap<>();
//Details to Hashmap
TempCountry.put("id", CountryID);
TempCountry.put("name", CountryName);
TempCountry.put("image", CountryImage);
//Hashmap to Countrylist
CountryList.add(TempCountry);
}
} catch (final JSONException e){
Log.e(TAG,e.getMessage());
ProgressDialog.setMessage("Error loading Data!");
}
}
return null;
}
This is the code for getting the JSON values, and i'm receiving an error
"No value for id"
What am I doing wrong?
You still have the "country" key to unwrap. Try like this:
for (int i = 1; i < Countries.length(); i++) {
JSONObject Country = Countries.getJSONObject(i).getJSONObject("country");
//Details
String CountryID = Country.getString("id");
String CountryName = Country.getString("name");
String CountryImage = Country.getString("image");
//Hashmap
HashMap<String, String> TempCountry = new HashMap<>();
//Details to Hashmap
TempCountry.put("id", CountryID);
TempCountry.put("name", CountryName);
TempCountry.put("image", CountryImage);
//Hashmap to Countrylist
CountryList.add(TempCountry);
}
First step is to create a new Java class model for the JSON - you can just copy and paste this.
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
public class Countries {
public class CountriesList implements Serializable {
private Country[] countries;
public Country[] getCountries() {
return countries;
}
public void setCountries(Country[] countries) {
this.countries = countries;
}
public ArrayList<Country> getCountriesAsList() {
if(countries == null || countries.length == 0) {
return new ArrayList<>();
} else {
return (ArrayList<Country>) Arrays.asList(countries);
}
}
}
public class Country implements Serializable {
private String id;
private String name;
private String image;
public Country() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
}
Now, it's simply converting the JSON into Java object like this. You can use that ArrayList for adapter or however you like.
protected Void doInBackground(Void... voids) {
HttpHandler Handler = new HttpHandler();
String jsonString = Handler.makeServiceCall(JSONUrl);
Countries.CountriesList countries = new Gson().fromJson(jsonString, Countries.CountriesList.class);
// this is the full list of all your countries form json
ArrayList<Countries.Country> countryList = countries.getCountriesAsList();
}
Note: you will need the Gson library to use the solution I showed above. I use that to convert JSON into Java object.
compile 'com.google.code.gson:gson:2.8.0'

Is it possible to display a changing arraylist in a Combo Box within a table in JavaFX?

I have run out of options and not sure where to go from here to display the data that I need.
I have setup a table of type "Consultation" with multiple columns in correspondence to a Consultation class. One field of the consultation class (students) is an arrayList of strings, holding the student identification numbers. I want to display this array list per record within the table via a drop down fashion. For this, I was thinking a drop down ComboBox.
Is it possible at all for this to be achieved? I have attempted to use this
solution to get Combo Boxes within a table cell, which works okay if the list is the same for all rows. My list changes for each record, so it doesnt really help my case
Note that the comboBox doesn't need to do anything either, just display the data
Relevant Methods within the controller class
public class ConsultationController {
private BackendInterface backendInterface;
#FXML TableView<Consultation> consultationTable;
private TableColumn<Consultation, Integer> consultIDColumn;
private TableColumn<Consultation, String> consultTitleColumn;
private TableColumn<Consultation, String> consultStartColumn;
private TableColumn<Consultation, String> consultEndColumn;
private TableColumn<Consultation, String> consultCategoryNameColumn;
private TableColumn<Consultation, String> consultPriorityNameColumn;
private TableColumn<Consultation, String> consultNoteColumn;
public void setupConsultationTable() {
//setup table columns
consultIDColumn = new TableColumn<>("Consultation ID");
consultIDColumn.setMinWidth(60);
consultIDColumn.setCellValueFactory(new PropertyValueFactory<>("consultationID"));
consultTitleColumn = new TableColumn<>("Title");
consultTitleColumn.setMinWidth(60);
consultTitleColumn.setCellValueFactory(new PropertyValueFactory<>("title"));
consultStartColumn = new TableColumn<>("Start Time");
consultStartColumn.setMinWidth(60);
consultStartColumn.setCellValueFactory(new PropertyValueFactory<>("startTime"));
consultEndColumn = new TableColumn<>("End Time");
consultEndColumn.setMinWidth(60);
consultEndColumn.setCellValueFactory(new PropertyValueFactory<>("endTime"));
consultCategoryNameColumn = new TableColumn<>("Category Name");
consultCategoryNameColumn.setMinWidth(60);
consultCategoryNameColumn.setCellValueFactory(new PropertyValueFactory<>("categoryName"));
consultPriorityNameColumn = new TableColumn<>("Priority Name");
consultPriorityNameColumn.setMinWidth(60);
consultPriorityNameColumn.setCellValueFactory(new PropertyValueFactory<>("priorityName"));
consultNoteColumn = new TableColumn<>("Note");
consultNoteColumn.setMinWidth(60);
consultNoteColumn.setCellValueFactory(new PropertyValueFactory<>("note"));
consultationTable.getColumns().addAll(consultIDColumn, consultTitleColumn, consultStartColumn, consultEndColumn, consultCategoryNameColumn,
consultPriorityNameColumn, consultNoteColumn);
}
public void loadAllConsultationTable(){
consultationTable.setItems(FXCollections.observableArrayList(backendInterface.returnConsultations()));
}
}
Consultation Class
public class Consultation {
private int consultationID, categoryID, priorityID;
private String title, startTime, endTime, studentZID, categoryName, priorityName, note;
private ArrayList<String> students;
public int getConsultationID() {
return consultationID;
}
public void setConsultationID(int consultationID) {
this.consultationID = consultationID;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public Consultation(int consultationID, String title, String startTime, String endTime, ArrayList<String> students,
int categoryID, String categoryName, int priorityID, String priorityName, String note) {
this.consultationID = consultationID;
this.title = title;
this.startTime = startTime;
this.endTime = endTime;
this.categoryID = categoryID;
this.students = new ArrayList<>(students);
this.categoryName = categoryName;
this.priorityID = priorityID;
this.priorityName = priorityName;
this.note = note;
}
public Consultation(int categoryID, int priorityID, String title, String startTime, String endTime,
ArrayList<String> students, String note) {
this.categoryID = categoryID;
this.priorityID = priorityID;
this.title = title;
this.startTime = startTime;
this.endTime = endTime;
this.students = new ArrayList<>(students);
this.note = note;
}
public String getStudentZID() {
return studentZID;
}
public void setStudentZID(String studentZID) {
this.studentZID = studentZID;
}
public void setTitle(String title) {
this.title = title;
}
public void setNote(String note) {
this.note = note;
}
public void setCategoryID(int categoryID) {
this.categoryID = categoryID;
}
public void setPriorityID(int priorityID) {
this.priorityID = priorityID;
}
public String getTitle() {
return title;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public void setPriorityName(String priorityName) {
this.priorityName = priorityName;
}
public String getNote() {
return note;
}
public String getCategoryName() {
return categoryName;
}
public String getPriorityName() {
return priorityName;
}
public int getCategoryID() {
return categoryID;
}
public int getPriorityID() {
return priorityID;
}
public ArrayList<String> getStudents() {
return students;
}
public String zIDsToString() {
String list = "";
for (String student : students) {
list += student + ",";
}
list = list.substring(0, list.length()-1);
return list;
}
}
ObservableList<Consultation> consultationData = FXCollections.observableArrayList();
tableDevices.setItems(consultationData);
int index = 0;
//here you have to add each instance of the class consultation
columnComboBox.setCellFactory(new Callback<TableColumn< Consultation, Consultation >, TableCell< Consultation, Consultation >>() {
#Override public TableCell< Consultation, Consultation> call(TableColumn< Consultation, Consultation > cbCol) {
return new TableCell< Consultation, Consultation >() {
final ComboBox comboBox = new ComboBox();
{
comboBox .setId(String.valueOf(index));
}
#Override public void updateItem(final Consultation consultation, boolean empty) {
super.updateItem(consultation, empty);
if (Consultation != null) {
if(index<=consultationData.size()){
System.out.println(consultation.getConsultationID());//just to see
comboBox.setItems((ObservableList) consultation.getStudents());
}
index++;
}
}
};
}
});
Here's how i taught a solution, i don't know if it will work for sure, i did a similar think populating with some buttons the rows of the table(so i thing the solution for populate each table cell with ComboBoxes it's not very far), where each button must do a different thing based on the data of the record.
I hope it would be useful for you.

Jaxb Arraylist Outputstream

My Xml Should look like:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<results>
<version>1.0</version>
<status>ok</status>
<lastUpdate>2011-11-21 09:23:59.0</lastUpdate>
<total>2</total>
<row>
<areaId></areaId>
<nameEng></nameEng>
<nameGer></nameGer>
</row>
… more <row></row> blocks …
</results>
How can i achieve this..?
At the moment i have the following.. but i dont know how i can return the album2 to the outputstream as a String...
List<Row> rows = new ArrayList<Row>();
while(rs.next()){
int albumId = rs.getInt(1);
int bookDocId = rs.getInt(2);
String picUrl = rs.getString(3);
String descEng = rs.getString(4);
String descGer = rs.getString(5);
Row row = new Row();
row.setAlbumId(albumId);
row.setBookDocId(bookDocId);
row.setPicUrl(picUrl);
row.setDescEng(descEng);
row.setDescGer(descGer);
rows.add(row);
}
Album album = new Album();
album.setRows(rows);
File file = new File("album.xml");
JAXB.marshal(album, file);
Album album2 = JAXB.unmarshal(file, Album.class);
file.deleteOnExit();
EDIT:
#XmlRootElement
public class Album {
private List<Row> rows = new ArrayList<Row>();
#XmlElement(name="row")
public List<Row> getRows(){
return this.rows;
}
public void setRows(List<Row> rows){
this.rows = rows;
}
Row.class:
public class Row {
private int albumId;
private int bookDocId;
private String picUrl;
private String descEng;
private String descGer;
public int getAlbumId() {
return albumId;
}
public int getBookDocId() {
return bookDocId;
}
public String getPicUrl() {
return picUrl;
}
public String getDescEng() {
return descEng;
}
public String getDescGer() {
return descGer;
}
public void setAlbumId(int albumId) {
this.albumId = albumId;
}
public void setBookDocId(int bookDocId) {
this.bookDocId = bookDocId;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl;
}
public void setDescEng(String descEng) {
this.descEng = descEng;
}
public void setDescGer(String descGer) {
this.descGer = descGer;
}
}
}
This is my code, it works well
#javax.xml.bind.annotation.XmlType
#javax.xml.bind.annotation.XmlAccessorType(javax.xml.bind.annotation.XmlAccessType.FIELD)
public class Album
{
long version;
String status;
java.util.List<Row> rows;
}
#javax.xml.bind.annotation.XmlType
#javax.xml.bind.annotation.XmlAccessorType(javax.xml.bind.annotation.XmlAccessType.FIELD)
public class Row
{
String areaId;
String nameEng;
String nameGer;
}
Test
public static void main(final String[] args) throws IOException
{
Album al = new Album();
List<Row> rows = new ArrayList<Row>();
final Row row1 = new Row();
row1.areaId = "area1";
row1.nameEng = "eng1";
row1.nameGer = "ger1";
final Row row2 = new Row();
row2.areaId = "area2";
row2.nameEng = "eng2";
row2.nameGer = "ger2";
rows.add(row2);
rows.add(row1);
al.status = "stat";
al.rows = rows;
final File file = new File("D:/test.xml");
final FileOutputStream out = new FileOutputStream(file);
JAXB.marshal(al, out);
final Album after = JAXB.unmarshal(file, Album.class);
assert after.status.equals(al.status);
assert after.rows.size() == al.rows.size();
}
You can change access to private and add getters, setters
To return like String use
ByteArrayOutputStream output = new ByteArrayOutputStream();
JAXB.marshal(al, output);
output.toString();
If you're asking how to write an Album to an output stream rather than write it to a file, then the answer is simple: JAXB.marshal(Object, OutputStream).
If you're asking how to transform an Album into an XML string, then the answer is also simple: JAXB.marshal(Object, String).
If you're asking something else, please clarify your question.

Categories

Resources