Issue
Here's my problem : I have a class Detenu :
public class Detenu {
private static String n_ecrou; // Unique id
private static String prenom;
private static String nom;
private static String date_naissance;
private static String lieu_naissance;
public Detenu(String p1, String p2, String p3, String p4, String p5) {
n_ecrou = p1;
prenom = p2;
nom = p3;
date_naissance = p4;
lieu_naissance = p5;
}
public static String getN_ecrou() {
return n_ecrou;
}
}
I also use JDBC to connect my application to an embedded database. This database implements a DETENU table with 5 columns, which are "N_ECROU", "PRENOM", "NOM", "DATE_NAISSANCE", "LIEU_NAISSANCE".
Then, I need to display all the Detenus stored in my database in a JavaFX TableView. So i use a getData() function like this :
public static ObservableList<Detenu> getData() {
ObservableList<Detenu> data = FXCollections.observableArrayList();
try {
// This part works fine
Connection con = DriverManager.getConnection("...");
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM DETENU);
while(result.next()) {
// Here comes the problem
// This shows all the different n_ecrou
System.out.println(result.getObject(1).toString());
data.add(new Detenu(result.getObject(1).toString(), result.getObject(2).toString(), result.getObject(3).toString(), result.getObject(4).toString(), result.getObject(5).toString()));
}
// This shows the same n_ecrou
System.out.println(data.get(0).getN_ecrou() + " " + data.get(1).getN_ecrou());
stmt.close();
result.close();
} catch(SQLException e) {
//Error process
}
return data;
}
By exemple, i have two Detenus in my database. The ObservableList i get back contains two Detenus, but the same one, the last in the databse. So when i want to display this data in a TableView, its creates two rows, but they are identical. Show in picture :
I dont have any idea why this is happening so any help will be thanked :)
PS : sorry for my english
Solution
All members of your Detenu
class are static
(shared by all instance of the class) that's why you have that behavior. Just remove the keyword on the fields and it should works.
Answered By - Baptiste Beauvais
Answer Checked By - Marilyn (JavaFixing Volunteer)