variable counter is not incrementing with adding new booking objects [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
// Entity class for booking
public class Booking {
private int distance;
private static int bookingId = 1000;
private int cabId;
private int customerId;
private int billingAmount;
public Booking() {
bookingId++;
System.out.println(bookingId);
}
}
// Service class for booking, I'm setting up all parameters here.
public class BookCab {
public Booking bookCab(int distance, int customerId){
Booking book = new Booking();
CabDao cabDao = new CabDaoImpl();
book.setDistance(distance);
book.setCustomerId(customerId);
book.setCabId(cabDao.getCabId()); //retrieving cab data from database
if(distance>10) {book.setBillingAmount(305 + (distance-10)*25);}
else if (distance <10 & distance>5) {
book.setBillingAmount(180 + (distance-5)*25);
}
else if (distance <5 & distance>1) {
book.setBillingAmount(100 + (distance-1)*20);
}
else book.setBillingAmount(100);
return book;
}
}
// This is DAO Implementation for accessing the Database.
public class BookingDaoImpl implements BookingDao {
Connection connection = null;
PreparedStatement ptmt = null;
ResultSet resultSet = null;
public BookingDaoImpl() {};
private Connection getConnection() throws SQLException {
Connection conn;
conn = DbUtil.getInstance().getConnection();
return conn;
}
public void addBooking(Booking booking) {
try {
String queryString = "INSERT INTO Booking(bookingId, customerId, cabId, distance, chargingAmount) VALUES(?,?,?,?,?)";
connection = getConnection();
ptmt = connection.prepareStatement(queryString);
ptmt.setInt(1, booking.getBookingId());
ptmt.setInt(2, booking.getCustomerId());
ptmt.setInt(3, booking.getCabId());
ptmt.setInt(4, booking.getDistance());
ptmt.setInt(5, booking.getBillingAmount());
ptmt.executeUpdate();
System.out.println("Data Added Successfully");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ptmt != null)
ptmt.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
// Driver class
public class MainView {
public static void main(String[] args) {
BookCab bookCab = new BookCab();
BookingDao bookingDao = new BookingDaoImpl();
bookingDao.addBooking(bookCab.bookCab(16, 691744));
}
}
/* Output
1001
Data Added Successfully
1001
Data Added Successfully
1001
Data Added Successfully
*/
Counter is not working
booking id is not increamenting
I've tried printing counter right after increamenting but its same there as well.

You only create one Booking instance in your main (or, to be exact, you create a single BookCab instance and call bookCab.bookCab(16, 691744), which creates the one Booking instance), which means it should print 1001.
If you run that application multiple times (which, based on your output, I assume you do), the Booking class will be loaded and initialized on each execution, so it will reset the counter back to 1000.
If you want the value of that static variable to live across executions of your applications, you must persist it in some file or DB table and load it when the Booking class is initialized.
P.S., you might want to store the current bookingId value in some instance variable, so that each Booking instance is associated with a unique bookingId value.

Your main method only creates a single booking, which will have Id 1001 every time you run the application.
Create a loop in your main method to make more than one booking, and check to see whether or not it's being incremented.
So change your main from
public static void main(String[] args) {
BookCab bookCab = new BookCab();
BookingDao bookingDao = new BookingDaoImpl();
bookingDao.addBooking(bookCab.bookCab(16, 691744));
}
to
public static void main(String[] args) {
for (int i = 0; i < 3; ++i) {
BookCab bookCab = new BookCab();
BookingDao bookingDao = new BookingDaoImpl();
bookingDao.addBooking(bookCab.bookCab(16, 691744));
}
}

static variable increment will not help you solve overall implementation problem here, it simply works as you expect when you create multiple objects for Booking class but catch here is what if the application is restarted ?
The counter is set back to starting point which is 1000.
#Eran has already indicated about this issue in the comment.

Related

Query a table in two date range with sql and java swing [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed yesterday.
Improve this question
I'm using two DatePickers for the a date range. My question is how to make it take the range it creates to take those two dates. The problem is from Java Swing. My problem is that it does not show me the dates in the range that I indicate, it only shows me all the dates. The data from the DatePicker is not being considered.
in this part place the jframe to enter the data range
public class ListPagos extends javax.swing.JInternalFrame {
public ListPagos() {
initComponents();
fechaini.setDate(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()));
fechafin.setDateToToday();
sqlconexion.conectar();
try {
PreparedStatement result = sqlconexion.sql.prepareStatement("SELECT * from pgs_pagos");
ResultSet rs = result.executeQuery();
DefaultListModel model = new DefaultListModel();
while (rs.next()) {
model.addElement(rs.getObject("pgs_fecha"));
}
/*jList1.setModel(model);*/
} catch (SQLException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
sqlconexion.desconectar();
}
private void verPagosActionPerformed(java.awt.event.ActionEvent evt) {
if (fechaini == null && fechafin == null) {
fechaini.setDate(LocalDate.now().with(TemporalAdjusters.firstDayOfNextMonth()));
fechafin.setDateToToday();
}
VisorListPagos ListPagos = new VisorListPagos(fechaini.getDate(), fechafin.getDate());
Dashboard.escritorio.add(ListPagos);
ListPagos.show();
}
in this part place the jframe place an internal jframe, to obtain the data from the jframe and print the table with the data
public class VisorListPagos extends javax.swing.JInternalFrame {
/**
* Creates new form VisorLisPagos
*/
JFrame Sucesor;
public VisorListPagos(){
initComponents();
}
public VisorListPagos(LocalDate fechaini, LocalDate fechafin) {
try {
initComponents();
Date fechainicial = Date.from(fechaini.atStartOfDay(ZoneId.systemDefault()).toInstant());
Date fechafinal = Date.from(fechafin.atStartOfDay(ZoneId.systemDefault()).toInstant());
sqlconexion.conectar();
ResultSet result = sqlconexion.read("SELECT P.pgs_clave, P.pgs_fecha, P.pgs_total, P.pgs_nombre, P.fct_folio, P.fct_tipo,P.pgs_status, P.pgs_fis_razon, P.pgs_fis_rfc, P.pgs_fis_UsoCFDi, P.pgs_fis_MetodoPago, P.pgs_fis_formaPago,PD.pgd_descripcion, PD.pgd_tipo FROM pgs_pagos P LEFT JOIN pgd_PagosDetalle PD ON P.pgs_clave = PD.pgs_clave '");
String [] nombrescol = {"Clave pago" ,//pgs_clave
"Fecha Pago" ,//P.pgs_fecha
"Total Pagos" ,//P.pgs_total
"Nombre" ,// P.pgs_nombre
"Folio Fct" ,//P.fct_folio
"Tipo Fct" ,//P.fct_tipo
"Status",//P.pgs_status
"Razon Fiscal" ,
"RFC" ,
"CFDI" ,
"Metodo Pago" ,
"Forma Pago" ,
"Descripcion" ,
"Tipo",
};
ResultSetMetaData data = result.getMetaData();
int columnas = data.getColumnCount();
Object [] row = new Object[columnas];
DefaultTableModel model = new DefaultTableModel(null, nombrescol);
while (result.next()) {
for (int i = 0; i < columnas; i++) {
row[i] = result.getObject(i+1);
}
model.addRow(row);
}
tabla1.setModel(model);
sqlconexion.desconectar();
} catch (SQLException ex) {
Logger.getLogger(VisorListPagos.class.getName()).log(Level.SEVERE, null, ex);
}
}

How I can use an auto increment in java for a register system? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 11 months ago.
Improve this question
I'm creating a register system for students using files, while I use the program the auto increment works fine, but when I ruin it again, the autoincremnt returns 1, also I am not allowed to use MySQL DataBase
I initialize it in the principal form
public class FrmPrincipal extends javax.swing.JFrame {
AdmonOrgSecuencial a = new AdmonOrgSecuencial("Datos.dat","Id.dat");
public static int idProveedor=1;
/**
* Creates new form FrmPrincipal
*/
public FrmPrincipal() {
initComponents();
Idp gen = new Idp(idProveedor);
a.idEscribir(gen);
}
This is the code I use to create and display the students
public class FrmAltas extends javax.swing.JDialog {
AdmonOrgSecuencial a = new AdmonOrgSecuencial("Datos.dat", "Id.dat");
/**
* Creates new form FrmAltas
*/
public FrmAltas(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
Idp proid;
int cve;
int clave;
int generador=FrmPrincipal.idProveedor;
proid= a.busquedaId(generador);
clave = proid.getIdp();
txtClave.setText(String.valueOf(clave));
}
private void btnGrabarActionPerformed(java.awt.event.ActionEvent evt) {
Idp proid;
int clave;
int generador= FrmPrincipal.idProveedor;
proid= a.busquedaId(generador);
clave = proid.getIdp();
String nombre = txtNombre.getText();
float promedio = Float.parseFloat(txtPromedio.getText());
Alumno alu = new Alumno(clave, nombre, promedio);
a.altas(alu);
a.bajasId(generador);
FrmPrincipal.idProveedor=generador+1;
int mas=FrmPrincipal.idProveedor;
Idp proid2= new Idp(mas);
a.idEscribir(proid2);
this.dispose();
}
These are the methods I use
public void idEscribir(Idp cve){
try{
{
fos = new FileOutputStream(idArchivo, true);
dos = new DataOutputStream(fos);
dos.writeInt(cve.getIdp());
cont++;
}
}
catch(FileNotFoundException e){
}
catch(IOException e){
System.out.println("Error:" +e.getMessage());
}finally{
cerrarArchivoEscritura();
}
}
public void bajasId(int elmr){
copiarIncremental(elmr);
borrarRenombrarId();
}
public void copiarIncremental(int idc){
int idg;
try{
fis = new FileInputStream(idArchivo);
dis = new DataInputStream(fis);
fos = new FileOutputStream("Temporario.dat");
dos = new DataOutputStream(fos);
while(true){
idg = dis.readInt();
if(idg != idc){
dos.writeInt(idg);
}
}
}catch(EOFException e){
}catch(IOException e){
System.out.println("Error"+ e.getMessage());
}finally{
cerrarArchivoLectura();
cerrarArchivoEscritura();
}
}
public void borrarRenombrarId(){
File original = new File(idArchivo);
original.delete();
File temporal = new File("Temporario.dat");
temporal.renameTo(original);
}
public Idp busquedaId(int clave){
boolean existe= false;
int cve;
try{
fis= new FileInputStream(idArchivo);
dis= new DataInputStream(fis);
while(existe == false){
cve = dis.readInt();
if(clave == cve){
existe = true;
return new Idp(clave);
}
}
return null;
}catch(FileNotFoundException e){
return null;
}
catch(EOFException e){
return null;
}catch(IOException e){
System.out.println("Error"+ e.getMessage());
return null;
}finally{
cerrarArchivoLectura();
}
}
Programs store their data in main memory. On program exit, all this data is lost. Therefore, when you restart your program, all the fields (like your auto-increment number) will no longer hold their former values.
To fix this, you need to write the auto-increment number to disk, e.g. by storing it in a file. Then, on program start, you want to load the previously saved number back into main memory.

Set value in Setter according to number of column in ResultSetMetaData

I am looking for dynamic approach in order to set the values in setter method, in which I fetch the total number of column from ResultSetMetaData, on based of those result, I want to set the values in corresponding setter method. I already prepared the snippet in my utility class.
public Integer extractData(ResultSet rs) throws SQLException, DataAccessException {
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for(int i = 1 ; i <= columnCount ; i++){
SQLColumn column = new SQLColumn();
String columnName = rsmd.getColumnName(i);
}
return columnCount;
}
Now the scenario is I want to set Pay_codes Of Employees, now there are total 95 paycode, but it differs in case of employees.
For example, Regular employees has 13 paycode, where as contactual employee has 6 codes, similarly society employees has 8 paycodes.
Now I need to show the list of paycodes on behalf of employee.
I passed EmployeeCode and I got the result.
Now The problem
whether I set all the column in my RowMapper like below
Paycode pc=new PayCode();
if(rs.getString("ESIC") != null){
pc.setESICCode(rs.getString("ESIC"));
}
if(rs.getString("EPF") != null){
pc.setEPFCode(rs.getString("EPF"));
}
if(rs.getString("Allowance") != null){
pc.setAllowance(rs.getString("Allowance"));
}
and many more columns........till 300+ lines
This seems very bad approach, because, Paycode can be increase or decrease as per client request.
So, I am looking for 2-3 line of dynamic code which set the values in setter according to the column name inside "ResultSetMetaData".So Kindly suggest me the best approach and help me to achieve the same.
However I am thinking of generic implementation, is generic do some magic, If yes > then how? please suggest me.
Use this code:
private void mapFields(PayCode p, String setterName, Object value) {
Method[] methods = PayCode.class.getDeclaredMethods();
for(Method method: methods){
if(method.getName().contains(setterName)){
try {
method.invoke(p, value);
break;
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
So you use Java reflection API with PayCode.class.getDeclaredMethods to get class methods, and then you iterate through method names searching for method that contains name of the property.
Once you find it you set the value to the object with method.invoke(p, value), and exit the loop.
You can make things faster if you store PayCode.class.getDeclaredMethods(), and then make a hash set with method name as a key, and method as a value Map<String, Method>:
static Map<String, Method> mapFields(Class clazz) {
Method[] methods = clazz.getDeclaredMethods();
Map<String, Method> result = new HashMap<>();
for(Method method: methods){
String methodName = method.getName();
if(methodName.indexOf("set") == 0){
result.put(methodName.substring(3), method);
}
}
return result;
}
and then use it:
Map<String, Method> fields = mapFields(PayCode.class);
if(fields.containsKey(name)){
try {
fields.get(name).invoke(p, value);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
You can use reflection
package com.test;
import java.lang.reflect.Method;
class PayCode {
private String esic;
private String epf;
public String getEsic() {
return esic;
}
public void setEsic(String esic) {
this.esic = esic;
}
public String getEpf() {
return epf;
}
public void setEpf(String epf) {
this.epf = epf;
}
#Override
public String toString() {
return "PayCode [esic=" + esic + ", epf=" + epf + "]";
}
}
public class DynamicSetter {
public static void main(String[] args) {
PayCode payCode = new PayCode();
try {
/**
* Here you can take "set" hardcoded and generate suffix "Esic"
* dynamically, may be using apache StringUtils or implement using
* Substring, based on your class setter methods.
*/
Method esicMethod = PayCode.class.getMethod("set" + "Esic", String.class);
esicMethod.invoke(payCode, "Test Paycode");
System.out.println("Check paycode in object : " + payCode);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can use HashMap<> to add all pay code in that. You can also implement gtter for each pay code to read from HashMap.
package com.test;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
class Employee {
private Map<String, String> payCodes = new HashMap<>();
private String epf;
public String getEsic() {
return payCodes.get("ESIC");
}
public String getEpf() {
return payCodes.get("EPF");
}
public Map<String, String> getPayCodes() {
return payCodes;
}
}
public class DynamicSetter {
public static void main(String[] args) {
}
public static Integer extractData(ResultSet rs) throws SQLException, DataAccessException {
while(rs.next()) {
Employee e = new Employee();
Map<String, String> payCodes = e.getPayCodes();
//set app paycode in payCodes, you can use column name as key and fetch value from result set.
}
}
}

How can I stop messages that are not ready to be processed from entering this loop in the doIT() method? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
when I set bpayrequestlist.size=maxmessagestoselect 1.e 20000, even messages which are not ready to be processed will enter the loop and it will turn into an infinite loop. How can I stop messages that are not ready to be processed from entering this loop?this is a banking system where messages like mt103 are being sent as a request by the customer. so those messages have to be processsed. i am encountering a problem in the while condition: while (bpayRequestsList!=null && bpayRequestsList.size() == maxMessagesToSelect);:
public class PaymentRequestPlugin implements IPlugin
{
BpayDeliveryService bpayDeliveryService = BpayDeliveryService.instance();
private final int ORACLE_MAX_IN_ELEMENTS = 1000;
private static final int MAX_SELECT_DEFAULT_VALUE = 20000;
private int maxMessagesToSelect = MAX_SELECT_DEFAULT_VALUE;
private Theme PAYMENT_REQUEST_PLUGIN = new Theme("PAYMENT_REQUEST_PLUGIN");
KundenZahlung kuza = null;
List<Long> kuzaList = new ArrayList<Long>();
List<Long> updatedBpayRequests = new ArrayList<Long>();
private BpayDeliveryService bpay = BpayDeliveryService.instance();
#Override
public void doIt() throws PluginException
{
List<BpayPaymentRequestData> bpayRequestsList = null;
Trace.trace(PAYMENT_REQUEST_PLUGIN, "PaymentRequestPlugin doIt()");
do
{
try
{
bpayRequestsList = bpay.getPaymentRequestPending(maxMessagesToSelect);
int lIndex = 0;
int uIndex = 0;
while (uIndex < bpayRequestsList.size())
{
uIndex = uIndex + ORACLE_MAX_IN_ELEMENTS;
if (uIndex > bpayRequestsList.size())
{
uIndex = bpayRequestsList.size();
}
List<BpayPaymentRequestData> bpayRequestsListAtOnce = bpayRequestsList.subList(lIndex, uIndex);
doAtOnce(bpayRequestsListAtOnce);
lIndex = uIndex;
}
}
catch (PluginException pe)
{
pe.notifyEvent();
}
catch (MVServiceNotAvailableException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
while (bpayRequestsList!=null && bpayRequestsList.size() == maxMessagesToSelect);
}
There are a few options I can suggest one would be utilized an array of objects and pass the message with a boolean value to it and this element of one would create an array of objects
Ex.
Public class objectOfOne
{
Public string message;
Public boolean truth;
//Constructor
Public class objectOfOne (String m; boolean t)
{
Message = m;
Truth= true;
}
//Insert get and set methods here
// So you can update if message
// Was processed
}//End objectOfOne class
In your main driver you'd call this to return The message to be processed after being processed you'd set the boolean for the object to true
Eg your if statement to check if message has been processed would be something like...
If(ArrayObject [at index].getTruth() == true)
Then process message
This is the way I would handle such a task it may not be the best way to do this but it's the best way I know how to do what I think your asking.

GWT: trying to retrive a list of objects through GWT AsyncCallback i got a list with only the last value

I'm trying to retrive a list of object with an AsyncCallback call. Everything look fine until I look at the list data in onSuccess procedure. Indeed, I receive a list with the right number of rows, but every rows is the same as the last retrived by SQL statement
this is the EntryPoint client module:
package com.fantaprica.client;
import java.util.List;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.fantaprica.shared.GameDay;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Fantaprica implements EntryPoint {
private final ODBConnectionAsync odbconnectionSvc = GWT
.create(ODBConnection.class);
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public void onModuleLoad() {
odbconnectionSvc
.getGameDayList(new AsyncCallback<List<GameDay>>() {
public void onFailure(Throwable caught) {
}
public void onSuccess(List<GameDay> result) {
System.out.println("#########################################");
System.out.println("OnModuleLoad");
for (int i = 0; i < result.size(); i++) {
System.out.println("index="+i);
System.out.println("result.get(i).getGameDayCompetition()="+result.get(i).getGameDayCompetition());
System.out.println("result.get(i).getGameDayCupFl()"+result.get(i).getGameDayCupFl());
System.out.println("result.get(i).getGameDayId()="+result.get(i).getGameDayId());
System.out.println("result.get(i).getGameDayOrder()="+result.get(i).getGameDayOrder());
System.out.println("result.get(i).getGameDaySeason()="+result.get(i).getGameDaySeason());
}
}
});
}
}
this is the implementation in server side:
package com.fantaprica.server;
import java.text.ParseException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Connection2DB {
public static ResultSet resultset(String p_sql_statement) throws ParseException {
//String db_file_name_prefix = "/home/dario/workspace/fantaprica/src/com/fantaprica/server/database/database";
//String db_file_name_prefix = "/home/dario/workspace/fantaprica/war/database/database";
String db_file_name_prefix = "/home/dario/Workspace/Fantaprica/war/fantaprica/database/database";
Connection con = null;
// connect to the database. This will load the db files and start the
// database if it is not alread running.
// db_file_name_prefix is used to open or create files that hold the
// state
// of the db.
// It can contain directory names relative to the
// current working directory
try {
Class.forName("org.hsqldb.jdbcDriver");
con = DriverManager.getConnection("jdbc:hsqldb:file:"
+ db_file_name_prefix, // filenames prefix
"sa", // user
""); // pass
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery(p_sql_statement);
System.out.println("query "+p_sql_statement+" eseguita");
statement.close();
con.close();
return rs;
} catch (ClassNotFoundException ex) {
Logger.getLogger(TestConnection.class.getName()).log(Level.SEVERE,
null, ex);
System.out.println("errore "+ex.toString());
return null;
} catch (SQLException ex) {
Logger.getLogger(TestConnection.class.getName()).log(Level.SEVERE,
null, ex);
ex.printStackTrace();
System.out.println("errore "+ex.toString());
return null;
}
}
public static void execstmt(String p_sql_statement) throws ParseException {
String db_file_name_prefix = "/home/dario/Workspace/Fantaprica/war/fantaprica/database/database";
Connection con = null;
// connect to the database. This will load the db files and start the
// database if it is not alread running.
// db_file_name_prefix is used to open or create files that hold the
// state
// of the db.
// It can contain directory names relative to the
// current working directory
try {
Class.forName("org.hsqldb.jdbcDriver");
con = DriverManager.getConnection("jdbc:hsqldb:file:"
+ db_file_name_prefix, // filenames prefix
"sa", // user
""); // pass
Statement statement = con.createStatement();
statement.executeUpdate(p_sql_statement);
System.out.println("statement "+p_sql_statement+" eseguito");
statement.close();
con.close();
} catch (ClassNotFoundException ex) {
Logger.getLogger(TestConnection.class.getName()).log(Level.SEVERE,
null, ex);
System.out.println("errore "+ex.toString());
} catch (SQLException ex) {
Logger.getLogger(TestConnection.class.getName()).log(Level.SEVERE,
null, ex);
ex.printStackTrace();
System.out.println("errore "+ex.toString());
}
}
}
when I run the code, I get these results:
#########################################
ODBConnectionImpl
Start creating the list
scanning resultset
v_game_day_tmp.getGameDayCompetition()=campionato
v_game_day_tmp.getGameDayCupFl()=false
v_game_day_tmp.getGameDayId()=0
v_game_day_tmp.getGameDayOrder()15
v_game_day_tmp.getGameDaySeason()2012/2013
0
index=0
v_game_day_list.get(i).getGameDayCompetition()=campionato
v_game_day_list.get(i).getGameDayCupFl()=false
v_game_day_list.get(i).getGameDayId()=0
v_game_day_list.get(i).getGameDayOrder()=15
v_game_day_list.get(i).getGameDaySeason()=2012/2013
scanning resultset
v_game_day_tmp.getGameDayCompetition()=campionato
v_game_day_tmp.getGameDayCupFl()=false
v_game_day_tmp.getGameDayId()=1
v_game_day_tmp.getGameDayOrder()14
v_game_day_tmp.getGameDaySeason()2012/2013
1
index=1
v_game_day_list.get(i).getGameDayCompetition()=campionato
v_game_day_list.get(i).getGameDayCupFl()=false
v_game_day_list.get(i).getGameDayId()=1
v_game_day_list.get(i).getGameDayOrder()=14
v_game_day_list.get(i).getGameDaySeason()=2012/2013
scanning resultset
v_game_day_tmp.getGameDayCompetition()=campionato
v_game_day_tmp.getGameDayCupFl()=false
v_game_day_tmp.getGameDayId()=2
v_game_day_tmp.getGameDayOrder()13
v_game_day_tmp.getGameDaySeason()2012/2013
2
index=2
v_game_day_list.get(i).getGameDayCompetition()=campionato
v_game_day_list.get(i).getGameDayCupFl()=false
v_game_day_list.get(i).getGameDayId()=2
v_game_day_list.get(i).getGameDayOrder()=13
v_game_day_list.get(i).getGameDaySeason()=2012/2013
scanning resultset
v_game_day_tmp.getGameDayCompetition()=mundialito
v_game_day_tmp.getGameDayCupFl()=false
v_game_day_tmp.getGameDayId()=3
v_game_day_tmp.getGameDayOrder()12
v_game_day_tmp.getGameDaySeason()2012/2013
3
index=3
v_game_day_list.get(i).getGameDayCompetition()=mundialito
v_game_day_list.get(i).getGameDayCupFl()=false
v_game_day_list.get(i).getGameDayId()=3
v_game_day_list.get(i).getGameDayOrder()=12
v_game_day_list.get(i).getGameDaySeason()=2012/2013
list created
#########################################
OnModuleLoad
index=0
result.get(i).getGameDayCompetition()=mundialito
result.get(i).getGameDayCupFl()false
result.get(i).getGameDayId()=3
result.get(i).getGameDayOrder()=12
result.get(i).getGameDaySeason()=2012/2013
index=1
result.get(i).getGameDayCompetition()=mundialito
result.get(i).getGameDayCupFl()false
result.get(i).getGameDayId()=3
result.get(i).getGameDayOrder()=12
result.get(i).getGameDaySeason()=2012/2013
index=2
result.get(i).getGameDayCompetition()=mundialito
result.get(i).getGameDayCupFl()false
result.get(i).getGameDayId()=3
result.get(i).getGameDayOrder()=12
result.get(i).getGameDaySeason()=2012/2013
index=3
result.get(i).getGameDayCompetition()=mundialito
result.get(i).getGameDayCupFl()false
result.get(i).getGameDayId()=3
result.get(i).getGameDayOrder()=12
result.get(i).getGameDaySeason()=2012/2013
As you can see, the list is created correctly in ODBConnectionImpl, and it is composted of 4 different lines.
But when I scan the list returned to AsyncCallback call, I have four equal rows, all equal to the last row from the ResultSet.
Thanks for help and advice,
Dario
I believe the problem is with the code in getGameDayList:
List<GameDay> v_game_day_list = new ArrayList<GameDay>();
GameDay v_game_day_tmp = new GameDay();
String v_sql_statement;
Remove GameDay v_game_day_tmp = new GameDay() from this block of code.
What you are doing is using the same object (v_game_day_tmp) 4 times in the list. As the while loop repopulates v_game_day_tmp and adds to the list, the previous entries in the list are still refering to the same object (v_game_day_tmp) and so will necessarily have the same value.
Do not use 1 temp object.
The object must be recreated with new(), populated and then added to the list.
Simply moving GameDay v_game_day_tmp = new GameDay(); to be the first line of while(rs.next()) should fix your problem.
Regards.
newnoise, SHiv16, I apologize, I made a wrong copy-paste. This is the code of getGameDayList procedure
public List<GameDay> getGameDayList() {
// TODO Auto-generated method stub
List<GameDay> v_game_day_list = new ArrayList<GameDay>();
GameDay v_game_day_tmp = new GameDay();
String v_sql_statement;
try {
v_sql_statement = "SELECT T1.\"game_day_id\",T1.\"game_day_date\",T1.\"game_day_competition\","
+ " T1.\"game_day_season\",T1.\"game_day_cup_fl\",T1.\"game_day_order\""
+ " FROM \"game_days\" T1 ORDER BY T1.\"game_day_order\" DESC";
System.out.println(" ------- ------- -------");
System.out.println("classe ODBConnectionImpl");
System.out.println("getGameDayList");
System.out.println("esecuzione statement " + v_sql_statement);
ResultSet rs = Connection2DB.resultset(v_sql_statement);
System.out.println("query eseguita");
int i = 0;
System.out.println("#########################################");
System.out.println("ODBConnectionImpl");
System.out.println("Start creating the list");
while (rs.next()) {
v_game_day_tmp.getGameDay(rs.getDate("game_day_date"),
rs.getString("game_day_competition"),
rs.getString("game_day_season"),
rs.getBoolean("game_day_cup_fl"),
rs.getInt("game_day_id"), rs.getInt("game_day_order"));
System.out.println("scanning resultset");
System.out.println("v_game_day_tmp.getGameDayCompetition()="+v_game_day_tmp.getGameDayCompetition());
System.out.println("v_game_day_tmp.getGameDayCupFl()="+v_game_day_tmp.getGameDayCupFl());
System.out.println("v_game_day_tmp.getGameDayId()="+v_game_day_tmp.getGameDayId());
System.out.println("v_game_day_tmp.getGameDayOrder()"+v_game_day_tmp.getGameDayOrder());
System.out.println("v_game_day_tmp.getGameDaySeason()"+v_game_day_tmp.getGameDaySeason());
System.out.println(i);
v_game_day_list.add(v_game_day_tmp);
System.out.println("index="+i);
System.out.println("v_game_day_list.get(i).getGameDayCompetition()="+v_game_day_list.get(i).getGameDayCompetition());
System.out.println("v_game_day_list.get(i).getGameDayCupFl()="+v_game_day_list.get(i).getGameDayCupFl());
System.out.println("v_game_day_list.get(i).getGameDayId()="+v_game_day_list.get(i).getGameDayId());
System.out.println("v_game_day_list.get(i).getGameDayOrder()="+v_game_day_list.get(i).getGameDayOrder());
System.out.println("v_game_day_list.get(i).getGameDaySeason()="+v_game_day_list.get(i).getGameDaySeason());
i++;
}
for(i=0;i<v_game_day_list.size();i++)
System.out.println("secondo loop v_game_day_list.get(i).getGameDayId()="+v_game_day_list.get(i).getGameDayId());
System.out.println("list created");
return v_game_day_list;
} catch (SQLException e) {
System.out.println("ODBConnectionImpl SQLException: "
+ e.toString());
return null;
} catch (ParseException e) {
System.out.println("ODBConnectionImpl ParseException: "
+ e.toString());
return null;
}
}
And this is the code of shared class GameDay:
package com.fantaprica.shared;
import java.util.Date;
import java.io.Serializable;
#SuppressWarnings("serial")
public class GameDay implements Serializable {
private int v_game_day_id;
private Date v_game_day_date;
private String v_game_day_competition;
private String v_game_day_season;
private boolean v_game_day_cup_fl;
private int v_game_day_order;
public GameDay() {
// TODO Auto-generated constructor stub
}
// questo metodo viene uitilizzato per l'UPDATE
public void setGameDay(int p_game_day_id,Date p_game_day_date, String p_game_day_competition,
String p_game_day_season, boolean p_game_day_cup_fl) {
v_game_day_id = p_game_day_id;
v_game_day_date = p_game_day_date;
v_game_day_competition = p_game_day_competition;
v_game_day_season = p_game_day_season;
v_game_day_cup_fl = p_game_day_cup_fl;
}
// questo metodo viene utilizzato per l'INSERT
public void setGameDay(Date p_game_day_date, String p_game_day_competition,
String p_game_day_season, boolean p_game_day_cup_fl) {
v_game_day_date = p_game_day_date;
v_game_day_competition = p_game_day_competition;
v_game_day_season = p_game_day_season;
v_game_day_cup_fl = p_game_day_cup_fl;
}
public void getGameDay(Date p_game_day_date, String p_game_day_competition,
String p_game_day_season, boolean p_game_day_cup_fl,
int p_game_day_id, int p_game_day_order) {
v_game_day_date = p_game_day_date;
v_game_day_competition = p_game_day_competition;
v_game_day_season = p_game_day_season;
v_game_day_cup_fl = p_game_day_cup_fl;
v_game_day_id = p_game_day_id;
v_game_day_order = p_game_day_order;
}
public Date getGameDayDate() {
return v_game_day_date;
}
public String getGameDayCompetition() {
return v_game_day_competition;
}
public String getGameDaySeason() {
return v_game_day_season;
}
public boolean getGameDayCupFl() {
return v_game_day_cup_fl;
}
public int getGameDayId() {
return v_game_day_id;
}
public int getGameDayOrder() {
return v_game_day_order;
}
}
I read that the problem could be a "static" implementation of the attribute of thr class, it's not this case, as GameDay class has no static attribute
Dario

Categories

Resources