Java Custom ArrayList All Entries the Same - java

I have a custom an arraylist setup to hold data for me.
However when I call the arraylist items all the items are the same.
My arraylist loader.
public static ArrayList<Animal> getTblHerd() throws Exception {
CC_H2 db = new CC_H2();
db.Connect(Variables.getStrConn(), Variables.getStrUser(),
Variables.getStrPassword(), "Embedded");
ResultSet rs = db.query("Select HERD_ID FROM tblHerd ORDER BY HERD_ID ASC");
ArrayList<Animal> alAnimals = new ArrayList<Animal>();
while (rs.next()) {
int i = rs.getInt("HERD_ID");
alAnimals.add(new Animal(i));
}
db.Disconnect();
return alAnimals;
}
Animal Constructor
public Animal(int intAnimal_ID) throws Exception{
CC_H2 db = new CC_H2();
db.Connect(Variables.getStrConn(), "admin", "", "Embedded");
ResultSet rs = db.query("Select * FROM tblHerd WHERE HERD_ID = "
+ intAnimal_ID);
while (rs.next()) {
setIntHerd_id(rs.getInt("Herd_ID"));
setStrHerd_Tag_Letter(rs.getString("Herd_Tag_Letter"));
setIntHerd_Tag_Num(rs.getInt("Herd_Tag_Num"));
setStrHerd_Tag_Color(rs.getString("Herd_Tag_Color"));
setStrHerd_Sex(rs.getString("Herd_Sex"));
setStrHerd_Type(rs.getString("Herd_Type"));
setDtHerd_Birthdate(rs.getDate("Herd_Birthdate"));
setIntHerd_Sire(rs.getInt("Herd_Sire"));
setIntHerd_Dam(rs.getInt("Herd_Dam"));
setIntHerd_Owner(rs.getInt("Herd_Owner"));
setDtHerd_TimeStamp(rs.getDate("Herd_TimeStamp"));
setStrHerd_Status(rs.getString("Herd_Status"));
setDtHerd_Status_Date(rs.getDate("Herd_Status_Date"));
}
db.Disconnect();
}

I think the code you listed should work as expected, the error is probably somewhere else.
Check the data in your database
Check the setters in the while loop do the right thing
Check that the fields in the Animal class are not static
If the problem persists, try to put something like System.out.println(rs.getInt("Herd_ID") + ": " + rs.getString("Herd_Tag_Letter")); into the where loop and check the output
Hope some of this helps :-)

you have created array list static
just remove static from there

Related

Strange behaviour with ArrayList

I'm in the process of building a basic database using csv files, and i'm currently testing the select function out when i ran into something strange.
private ArrayList<Record> selectField(String selectTerm)
{
Log.log("Selection " + selectTerm,2,"DB_io");
ArrayList<Record> ret = new ArrayList<Record>();
if (titleRow.values.contains(selectTerm))
{
Log.log("Adding values to " + selectTerm);
int ordinal = titleRow.values.indexOf(selectTerm);
Log.log("Ordinal " + ordinal);
List<String> tempList = new ArrayList<String>();
for (Record r : data)
{
List<String> tempList = new ArrayList<String>();
tempList.add(r.values.get(ordinal));
Record s = new Record(tempList);
ret.add(s);
tempList.clear();
}
Log.log("Number of records in ret " + ret.size());
for (Record t : ret)
{
Log.log(t.toString());
}
}
else
{
Log.log("keyField does not contain that field");
return null;
}
Log.log("Values " + ret.toString());
return ret;
}
When i do this, the part where it logs t.ToString() shows the record to be empty, whereas if i log it before tempList.clear(), it shows the record to be containing data like it should.
If i move the tempList declaration into the Record r : data loop, then it works fine and the Record t : ret loop works outputs the contents of the record like it should
Why is this?
Edit : Record class
public class Record
{
List<String> values = new ArrayList<String>();
public Record(List<String> terms)
{
this.values = terms;
}
public Record(String[] s)
{
this.values = Arrays.asList(s);
}
public String toString()
{
return values.toString();
}
}
Your Record instance holds a reference to the ArrayList instance you passed to its constructor. Therefore, when you call tempList.clear(), you clear the same List that your Record instance is holding a reference to.
You shouldn't call tempList.clear(), since you are creating a new ArrayList in each iteration of your loop anyway.
you are referencing object from more than one place and clear method is cleaning object by setting its reference to null:
instead of ret.add(s); you can use ret.add(s.clone());

How to store 2 integer in array list from result set and how to retrieve it

How to store 2 integer in array list from result set and how to retrieve it.
I am trying to store the 2 integer to my array list and i don't know if get it correctly because when I am trying to retrieve it, it prints something like this
'tryCheckout$checkout#4f4fffa4' Thanks guys. This is my code so far.
public class checkout{
public int roomtypeid,itemid;
}
ArrayList<checkout> returncheckout = new ArrayList<checkout>();
try{
*String query ="select ri.item_id, ri.roomtype_id from roomtype_tb as rt , roomtypeitem_tb as ri , room_tb as r , reserverooms_tb as rr where rt.roomtype_id = r.roomtype_id and rt.roomtype_id = ri.roomtype_id and ri.roomtype_id = r.roomtype_id and r.room_id = rr.room_id and rr.reservation_id = 10";
PreparedStatement pst =conn.prepareStatement(query);
ResultSet rs = pst.executeQuery();
while(rs.next())
{
checkout out = new checkout();
out.roomtypeid = rs.getInt("ri.roomtype_id");
out.itemid = rs.getInt("ri.item_id");
returncheckout.add(out);
}
returncheckout.forEach(System.out::println);
}catch(Exception e)
{
e.printStackTrace();
}*
I didn't see your checkout class. Now I do. Change it to
public class checkout{
public int roomtypeid,itemid;
#Override
public String toString()
{
return "roomtypeid =" + roomtypeid + ", itemid=" + itemid;
}
}
In your checkout class override the toString() method. That is a special method that gets called when an object gets passed to System.out.println. It will look something like this:
#Override
public String toString()
{
return "roomType=" + roomType + ", id=" + id;//Not sure what your variables are. You will need to change this line
}
I think your code is doing what you want, you just need the toString() method to print the result out like you want it.
Java is actually returning the memory address for the object checkout. That is the weird numbers that are output to the screen. Add something like this to the checkout class.
public class checkout{
public int roomtypeid, itemid;
#Override
public String toString()
{
return "Room Type ID: " + roomtypeid + " Item ID: " + itemid";
}
}
The toString() method is called when the object is printed.

returning 2 different values

i'm working with java in eclipse.I am trying to take 2 variables from my database and write it to an excel.My only problem is returning 2 different values(an integer and a string) from db reader method and send it to excel writer method which are in different classes.
Here is my db reader class:
public class DbConnection {
public void createConnection(String choice) {
try {
String myDriver = "com.mysql.jdbc.Driver";
String db = "jdbc:mysql://localhost/digiturkschema";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(db, "root",
"*****");
Statement st = conn.createStatement();
switch (choice) {
case "write":
ResultSet rs = st.executeQuery("SELECT * FROM channelstable");
while (rs.next()) {
int channelId = rs.getInt("channelNo");
String channelName = rs.getString("channelName");
}
}
} catch (Exception exception) {
System.out.print(exception.getStackTrace());
}
}
}
I need to return "channelId" and "channelName" from this method to this method:
public class WritingToExcel {
public void Write() throws IOException {
try {
JFileChooser f = new JFileChooser();
f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
f.showSaveDialog(null);
System.out.println(f.getCurrentDirectory());
System.out.println(f.getSelectedFile());
String direction = f.getSelectedFile().toString() + "\\DigiTurkKanalListesi.xls";
WritableWorkbook workbook = Workbook.createWorkbook(new File(direction));
WritableSheet sheet = workbook.createSheet("Kanal Listesi", 0);
Label label = new Label(0, 0, "A label record");
sheet.addCell(label);
Number number = new Number(2, 1, 3.1459);
sheet.addCell(number);
workbook.write();
workbook.close();
} catch (WriteException e) {
e.getStackTrace();
}
}}
I know that writingToExcel class is not completed and it's ok,i can finish it if i can take these two variables to this class.By the way i am using MVC pattern so i have a controller class between them.I can write it too if it's necessary.
As #Ascalonian said, you can use Map or HashMap.
for example:
Map<Integer, String> channelInfo = new HashMap<Integer, String>();
You can also (but should not):
Create a new class with the values you need and return that class. (You will be doing extra work which you don't really need to.)
Create setter methods for those variables and use it before calling the method to write to excel. (requires caution as you can end up with undesired values if you mess the code)
There are multiple options
ArrayList<Objects> : During Iterating the resultSet prepare temporary List say tempList insert items into tempList and then after each iteration add tempList to Main List , Since ArrayList is a sequential list. So, insertion and retrieval order is the same. So you can return this from your dbReader() method .Then use them wherever you want
Your Arraylist will look like this
[ [1,Channel 1] , [2,Channel 2] , [3,Channel 3] ]
Map if order is important prefer LinkedHashMap if order is not your primary concern then opt for HashMap

ArrayList method return

I'm working in a project with DB. There are a method that collect info from the DB and set the info in ArrayList:
public ArrayList<Director> listAll(){
ArrayList<Director>list = new ArrayList<Director>();
Director direc = new Director();
int cont=0;
String sql = "select * from director;";
try{
ResultSet res = objBBDD.sentencia.executeQuery(sql);
while(res.next()){
direc.setCode(res.getInt("CODE"));
direc.setName(res.getString("NAME"));
direc.setNationality(res.getString("NATIONALITY"));
direc.setOscar(res.getInt("OSCAR"));
list.add(direc);
// THIS IS USE TO CONFIRM IF IT WORKS ///////////////////////////////////////
// JOptionPane.showMessageDialog(null,"Code:"+list.get(cont).getCode()+"Nombre"+list.get(cont).getName());
// cont++;
}
}catch (SQLException e) {
e.printStackTrace();
}
return list;
}
I use JOptionPane.showMessageDialog to see if I get info from DB and is added correctly to de ArrayList, and it's works.
Now the ArrayList back the invoker class, this is the method:
private void stackArray(){
ArrayList<Director>arrayDir = new ArrayList<Director> ();
ArrayList<Director>arrayDir = conexion.listAll();
// JOptionPane.showMessageDialog(null,"Code:"+arrayDir.get(0).getCode()+"Name"+arrayDir.get(0).getName());
// JOptionPane.showMessageDialog(null,"Code:"+arrayDir.get(1).getCode()+"Name"+arrayDir.get(1).getName());
// JOptionPane.showMessageDialog(null,"Code:"+arrayDir.get(2).getCode()+"Name"+arrayDir.get(2).getName());
}
Again I use the JOptionPane.showMesageDialog to show the first three positions, but it's not work, the problem, as far as I've seen, is all the positions have the same object saved (exactly the last).
Summarizing the ArrayList have the same object (last in DB), there are no problems at run or compile.
I don't know if I write something bad, or just a noob fail.
the problem, as far as I've seen, is all the positions have the same
object saved (exactly the last).
You are changing value of same instance Director. Thats why, you seen the last value of Director object. You should create new instance of Director with iteration of while loop.
ResultSet res = objBBDD.sentencia.executeQuery(sql);
while(res.next){
Director direc = new Director();// Declare Director instance here.
.....
list.add(direc);
}

Iterartor - How to traverse for specific records

I have executed a query using JDBC and traversing the resultset I have stored all fields in List in java.
List<String> dataList=new ArrayList<String>();
while(res.next())
{
dataList.add(res.getString(1));
dataList.add(res.getString(2));
dataList.add(res.getString(3));
dataList.add(res.getString(4));
dataList.add(res.getString(5));
dataList.add(res.getString(6));
dataList.add(res.getString(7));
}
Iterator<String> it= dataList.iterator();
As I have added directly into list so how can I get this 7 fields while traversing the iterator.
Means:
while(it.hasNext())
{
String f1=it.next();
}
Like wise everytime I want 7 fields at a time
and next 7, next 7....... so on
Using this while loop how can I get those 7 fields (one row in table having 7 field) at a time.
I get little bit confuse here. Please help me.
Thanks
What you want to do is actually create another object that stores all seven of the values.
Then create a list of these entries so that you can access one row at a time, which is what I think you are asking.
First create a class for the row.
private static class Entry {
String[] row;
public Entry ( ResultSet r ) {
row = new String [ 7 ];
for (int i = 1; i <= 7; i++) {
row[i] = r.getString(i);
}
}
}
Using that, you can then create a list of Entry objects.
List<Entry> entryList = new ArrayList <Entry> ();
while(res.next())
{
entryList.add ( new Entry ( res ) );
}
Then, you can go ahead and loop through entryList and get any specific entry you would want.
Of course, if you have specific values, it might be wise to create instance variables of type String for Entry rather than an array of Strings.
By that I mean you could do this:
private static class Entry {
String column1; // rather than name column1 use what the column semantically represents
String column2;
// ...
public Entry ( ResultSet r ) {
column1 = r.getString(1);
// ...
}
This way, you can also calls like r.getInt(i) for certain columns which have an different type other than String.
Good luck!
I think your List declaration should be
List<Any DAO Object> instead of List<String>
While fetching from resultset, create a DAO object, add all fetched data into that object and then add that object into the list.
Then you can iterate and get each DAO object at each iteration.
You can use DatabaseMetaData class,
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost/testdb";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
public static void main(String[] args) throws Exception {
Class.forName(DRIVER);
Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
DatabaseMetaData metadata = connection.getMetaData();
ResultSet resultSet = metadata.getColumns(null, null, "users", null);
while (resultSet.next()) {
String name = resultSet.getString("COLUMN_NAME");
String type = resultSet.getString("TYPE_NAME");
int size = resultSet.getInt("COLUMN_SIZE");
System.out.println("Column name: [" + name + "]; type: [" + type + "]; size: [" + size + "]");
}
connection.close();
}

Categories

Resources