Reputation: 3941
I have a ListView which is filled with artwork names (from SQLite database), these are strings and the names are not primary keys (not unique). Of course each artwork has its own ID (primary key).
What I do, I select one artwork from this list and pass it as a string argument to a button, which creates additional informations (that is not neccessary for this question).
But I select the name, now I need to get the ID from this selected artwork as foreign key.
Of course I can create a select query like this:
"select * from Artwork where Name = ?";
and then get the ID from the artwork with this name, but as I said before, there can be multiple artworks with the same name, so this is not good.
The Plan B which I have is to display in the ListView also the IDs of the the artworks, then If you select one artwork, you could slice the String at " "
and take work with the list argument which contains the ID.
But that does not feel right.
Thanks! I hope you understood what I need, if not I could provide code, but there is really a lot.
Upvotes: 1
Views: 1347
Reputation: 209340
You are confusing what is displayed in the list view (the data) with how it is displayed (the view). You want the data to consist of objects containing both the id and the name. You want the view to simply display the name of those objects.
Create a class representing the Artwork
that contains both the id and the name:
public class Artwork {
private final int id ;
private final String name ;
public Artwork(int id, String name) {
this.id = id ;
this.name = name ;
}
public String getName() {
return name ;
}
public int getId() {
return id ;
}
}
Have your database code return a list of Artwork
objects, and define your list view:
ListView<Artwork> listView = new ListView<>();
listView.getItems().addAll(getArtworkFromDatabase());
Finally, to configure how the list view is displayed, set the cell factory:
listView.setCellFactory(lv -> new ListCell<Artwork>() {
@Override
public void updateItem(Artwork artwork, boolean empty) {
super.updateItem(artwork, empty) ;
setText(empty ? null : artwork.getName());
}
}
Now you can get whatever data you need from the selected item:
Artwork selected = listView.getSelectionModel().getSelectedItem();
int selectedId = selected.getId();
String selectedName = selected.getName();
Upvotes: 4