Why does the same date appear on all Users?

2

I am in Java, and I want to show the users that I have in the database, I make the query and it collects it well, I insert them well in an ArrayList and when I show it, only the date of birth of the last user appears. Why?

try {
        sentencia = conexion.createStatement();
        String consulta = 
                "SELECT Nombre, Apellidos, Telefono, Fecha_Nacimiento, "
                + "Domicilio, Ciudad, DNI, Bloqueado, Usuario, Tipo FROM usuarios;";
        ResultSet resultado = sentencia.executeQuery(consulta);
        while (resultado.next()) {
            calendario.set(Integer.parseInt(resultado.getString(4).substring(0, 4)), 
                Integer.parseInt(resultado.getString(4).substring(5, 7)),
                Integer.parseInt(resultado.getString(4).substring(8, 10)));
            mostrarUsuario = new Usuario(resultado.getString(1), resultado.getString(2),
            resultado.getInt(3), calendario, resultado.getString(5), resultado.getString(6),
            resultado.getString(7), resultado.getString(8).charAt(0), resultado.getString(9),
            resultado.getString(10).charAt(0));
            listaUsuarios.add(mostrarUsuario);
            System.out.println(mostrarUsuario.toString());
        }
        resultado.close();
        // MOSTRAMOS LOS USUARIOS
        mostrarUsuarios();
    } catch (NumberFormatException | SQLException e) {
        JOptionPane.showMessageDialog(rootPane, "ERROR AL CARGAR DATOS DE LA BASE DE DATOS\n"
                + "Detalles del Error: " + e.getMessage(), "Error en el catch", JOptionPane.ERROR_MESSAGE);
    }

private void mostrarUsuarios() {
    try {
        // MODELO DE LA TABLA
        String[] columnas = {"Nombre", "Apellidos", "Nº Teléfono", 
            "Fecha Nacimiento", "Domicilio", "Ciudad", "DNI", "Bloqueado", "Usuario", "Tipo"};
        DefaultTableModel modelo = new DefaultTableModel(null, columnas);
        for (Usuario mostrar : listaUsuarios) {
            calendario.set(mostrar.getFechaNacimiento().get(Calendar.YEAR),
              mostrar.getFechaNacimiento().get(Calendar.MONTH), mostrar.getFechaNacimiento().get(Calendar.DATE));
            String[] filas = {mostrar.getNombre(), mostrar.getApellidos(),
                String.valueOf(mostrar.getTelefono()), 
                String.valueOf(calendario.get(Calendar.DATE) + "-" + calendario.get(Calendar.MONTH)
                + "-" + calendario.get(Calendar.YEAR)), mostrar.getDomicilio(), 
                mostrar.getCiudad(), mostrar.getDni(), String.valueOf(mostrar.getBloqueado()),
                mostrar.getUsuario(), String.valueOf(mostrar.getTipo())};
            modelo.addRow(filas);
            tablaUsuarios.setModel(modelo);
            System.out.println(mostrar.toString());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Output: Uploaduser:

Samuel ',' a ',' 987654321 ',' 2018-7-9 ',' a ',' a ',' a ',' N ',' User ',' null ',' A asdasd ' , 'Surname', '123456789', '2018-10-9', 'Address', 'City', 'd', 'N', 'AAAAAAAA', 'null', 'N Kia', 'ape', '656298534', '2008-11-26', 'Villa pelisa', 'pelusoide', '5454564', 'N', 'kia', 'null', 'T

ShowUser: Samuel ',' a ',' 987654321 ',' 2008-11-26 ',' a ',' a ',' a ',' N ',' User ',' null ',' A asdasd ',' Surnames ',' 123456789 ',' 2008-11-26 ',' Address ',' City ',' d ',' N ',' AAAAAAAA ',' null ',' N Kia ',' ape ',' 656298534 ',' 2008-11-26 ',' Villa pelisa ',' pelusoide ',' 5454564 ',' N ',' kia ',' null ',' T

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Usuarios;

import java.util.Calendar;

/**
 *
 * @author Programador
 */
public class Usuario {
    private String nombre, apellidos, domicilio, ciudad, dni, usuario, contrasena;
    private int telefono;
    private char bloqueado, tipo;
    private Calendar fechaNacimiento = Calendar.getInstance();

    // CONSTRUCTOR PARAMETRIZADO
    public Usuario(String nombre, String apellidos, int telefono, Calendar fechaNacimiento, 
            String domicilio, String ciudad, String dni, char bloqueado, String usuario,
            String contrasena, char tipo) {
        this.nombre = nombre;
        this.apellidos = apellidos;
        this.telefono = telefono;
        this.fechaNacimiento = fechaNacimiento;
        this.domicilio = domicilio;
        this.ciudad = ciudad;
        this.dni = dni;
        this.bloqueado = bloqueado;
        this.usuario = usuario;
        this.contrasena = contrasena;
        this.tipo = tipo;
    }

    // CONSTRUCTOR PARAMETRIZADO PARA MOSTRAR LOS DATOS
    Usuario(String nombre, String apellidos, int numTelefono, Calendar fechaNacimiento,
            String domicilio, String ciudad, String dni, char bloqueado, String usuario, char tipo) {
        this.nombre = nombre;
        this.apellidos = apellidos;
        this.telefono = numTelefono;
        this.fechaNacimiento = fechaNacimiento;
        this.domicilio = domicilio;
        this.ciudad = ciudad;
        this.dni = dni;
        this.bloqueado = bloqueado;
        this.usuario = usuario;
        this.tipo = tipo;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public String getApellidos() {
        return apellidos;
    }

    public void setApellidos(String apellidos) {
        this.apellidos = apellidos;
    }

    public String getDomicilio() {
        return domicilio;
    }

    public void setDomicilio(String domicilio) {
        this.domicilio = domicilio;
    }

    public String getCiudad() {
        return ciudad;
    }

    public void setCiudad(String ciudad) {
        this.ciudad = ciudad;
    }

    public String getDni() {
        return dni;
    }

    public void setDni(String dni) {
        this.dni = dni;
    }

    public String getUsuario() {
        return usuario;
    }

    public void setUsuario(String usuario) {
        this.usuario = usuario;
    }

    public String getContrasena() {
        return contrasena;
    }

    public void setContrasena(String contrasena) {
        this.contrasena = contrasena;
    }

    public int getTelefono() {
        return telefono;
    }

    public void setTelefono(int telefono) {
        this.telefono = telefono;
    }

    public char getBloqueado() {
        return bloqueado;
    }

    public void setBloqueado(char bloqueado) {
        this.bloqueado = bloqueado;
    }

    public char getTipo() {
        return tipo;
    }

    public void setTipo(char tipo) {
        this.tipo = tipo;
    }

    public Calendar getFechaNacimiento() {
        return fechaNacimiento;
    }

    public void setFechaNacimiento(Calendar fechaNacimiento) {
        this.fechaNacimiento = fechaNacimiento;
    }

    @Override
    public String toString() {
        return nombre + "', '" + apellidos + "', '" + telefono + "', '" + (fechaNacimiento.get(Calendar.YEAR)
            + "-" + fechaNacimiento.get(Calendar.MONTH) + "-" + fechaNacimiento.get(Calendar.DATE)) + "', '"
                + domicilio + "', '" + ciudad + "', '" + dni + "', '" +
                bloqueado + "', '" + usuario + "', '" + contrasena + "', '" + tipo;
    }

}
    
asked by Samuel Tena 12.11.2018 в 14:35
source

1 answer

2

I do not know what type is the variable calendario (I assume Calendar), but the problem you have is that you never re-initialize it, but you reuse the same object again and again, modifying it.

Therefore, the last modification is the one that counts, since all users share the same instance.

Typically, you use objects from class Date to save dates and simply use the Calendar class to generate them (although if you work with Java 8 or later you should look at the classes in the java.time package). In any case I put the code that solves the problem as you have the user class.

 while (resultado.next()) {
     Calendar calendario = Calendar.getInstance(); //nueva instancia dentro del bucle       calendario.set(Integer.parseInt(resultado.getString(4).substring(0, 4)), 
     Integer.parseInt(resultado.getString(4).substring(5, 7)),
     Integer.parseInt(resultado.getString(4).substring(8, 10)));
     mostrarUsuario = new Usuario(resultado.getString(1), resultado.getString(2),
     resultado.getInt(3), calendario, resultado.getString(5), resultado.getString(6),
     resultado.getString(7), resultado.getString(8).charAt(0), resultado.getString(9),
     resultado.getString(10).charAt(0));
     listaUsuarios.add(mostrarUsuario);
     System.out.println(mostrarUsuario.toString());
 }

The Date class is not immutable, as is the class LocalDateTime but you should treat it as such to avoid problems.

    
answered by 12.11.2018 / 15:03
source