I am getting weird return in memory for my linked list. I'm not sure what the cause is... After the code iterates through the database and attempts to put my data into the list... the linked list shows all the elements being the same or better yet it sets all the values to the last record set.
public LinkedList<Property> GetProperties()
{
System.out.println("Get Properties...");
Statement stmt = null;
LinkedList<Property> properties = new LinkedList<Property>();
String sql = "SELECT * FROM PROPERTIES;";
System.out.println(strCurrentDBFile);
ResultSet rs = null;
try{
Property prpty = new Property();
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:" + strCurrentDBFile);
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
prpty.strPrptyName = rs.getString(1);
prpty.strPrptyAddress1 = rs.getString(2);
prpty.strPrptyAddress2 = rs.getString(3);
prpty.strPrptyCity = rs.getString(4);
prpty.strPrptyState = rs.getString(5);
prpty.strPrptyZipCode = rs.getString(6);
properties.push(prpty);
}
rs.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
return properties;
}
You want to create a new instance of Property
for each record. Currently you've got this
Property prpty = new Property();
... outside the loop, so your linked list consists of many references to the same object. That line should be inside the loop, so that you create a new instance, populate it, and then add a reference to it into your linked list.
If that doesn't explain the problem to you clearly enough, I'd suggest revisiting how objects and references work in Java before you go any further.
Additionally, I'd strongly recommend using a try-with-resources statement for your resources, rather than manually closing them.
See more on this question at Stackoverflow