0

I'm creating a software in Java which should be able to register artists, Albums and Tracks as well.

Everything is connected to a MySQL DB, the software requires only artist name, I show you the methods I created. I'm sorry many of the names are in Spanish, but this is for my school and I can't use too many english words. I think you can understand it

This is the class Conexión which makes the connection to the DB:

public class Conexion {

Connection conexion=null;

/*Conectamos a la Base de Datos*/

public Conexion(){
    try{
        Class.forName("com.mysql.jdbc.Driver"); 
        conexion=DriverManager.getConnection("jdbc:mysql://localhost/chinook", "root", "");
    }catch(Exception excepcion){
        excepcion.printStackTrace();
    }
}

/*Devolvemos la conexion*/

public Connection getConnection(){
    return conexion;
}

/*Cerramos la conexión a la Base de Datos*/

public void desconectar(){
    try{
        conexion.close();
    }catch(Exception excepcion){
        excepcion.printStackTrace();
    }
 }

}

This is the class Coordinador, this class is used to make the union among different classes (following model MVC), I paste you the part from adding the artist, the others are just related to views:

public void addArtista(ArtistaVO artistaVO){
    miLogica.validarRegistroArtista(artistaVO);
}

The class ArtistaVO where I create get and set of the artist:

public class ArtistaVO {

  private int idArtista;
  private String nombreArtista;

  public int getIdArtista(){
     return idArtista;
  }

  public void setIdArtista(int idArtista){
     this.idArtista=idArtista;
  }

  public String getNombreArtista(){
      return nombreArtista;
  }

  public void setNombreArtista(String nombreArtista){
     this.nombreArtista=nombreArtista;
  }
}

Method to register the artist:

 public void addArtista(ArtistaVO artistaVO){

    Conexion conexion=new Conexion();

    try{
        //Insertamos los datos del Artista
        PreparedStatement  sqlAddArtist=conexion.getConnection().prepareStatement("INSERT into artist values(?,?)");
        ResultSet resultado=sqlAddArtist.executeQuery();
        while(resultado.next()){
            sqlAddArtist.setString(1, artistaVO.getNombreArtista());
            sqlAddArtist.setInt(2, getMaxId()+1);
        }
        JOptionPane.showMessageDialog(null, "Se ha añadido exitosamente","Información",JOptionPane.INFORMATION_MESSAGE);
        sqlAddArtist.close();
        conexion.desconectar();

    }catch(SQLException excepcion){
        System.out.println(excepcion.getMessage());
        JOptionPane.showMessageDialog(null,"No se registro", "Error", JOptionPane.ERROR_MESSAGE);
    }
}

This method is used to create Artist ID:

  public int getMaxId(){
    int id=0;
    Conexion conexion=new Conexion();

    try{
        Statement sqlMaxId=conexion.getConnection().createStatement();
        ResultSet resultado=sqlMaxId.executeQuery("SELECT max(ArtistId) from artist");

        if(resultado.next()){
            id=resultado.getInt(0);
        }

        conexion.desconectar();
        sqlMaxId.close();
    }catch(SQLException excepcion){
        System.out.println(excepcion.getMessage());
    }

    return id;
}

This belongs to the window which register the artist after clicking the button:

  public void actionPerformed(ActionEvent evento) {

    if(evento.getSource()==botonAñadir){

        try{
            ArtistaVO artistaVO=new ArtistaVO();
            artistaVO.setNombreArtista(campoTextoArtista.getText());

            miCoordinador.addArtista(artistaVO);
        }catch(Exception excepcion){
            JOptionPane.showMessageDialog(null, "Error al añadir Artista", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

}

The error I get is Error al añadir Artista (Error adding Artist), I don't know where the failure can be.

This is the exception I get:

java.lang.NullPointerException
at controlador.Coordinador.addArtista(Coordinador.java:108)
at vista.VistaArtistasAdd.actionPerformed(VistaArtistasAdd.java:70)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

This is the method validarRegistroArtista:

 public void validarRegistroArtista(ArtistaVO artistaVO){
    ArtistaDAO artistaDAO;

    if(artistaVO.getIdArtista()>=0){
        artistaDAO=new ArtistaDAO();
        artistaDAO.addArtista(artistaVO);
    }else{
        JOptionPane.showMessageDialog(null, "Debe de introducirse algún numero de ID", "Advertencia", JOptionPane.WARNING_MESSAGE);
    }
}
NeoChiri
  • 296
  • 4
  • 18
  • error is at line `Coordinador.java:108` and is a `NullPointerException`... cause? we should see the code of: `miLogica.validarRegistroArtista(artistaVO);` but I can bet `artistaVO == null`.... also... http://es.stackoverflow.com – Jordi Castilla Apr 27 '16 at 10:11
  • Just added the method – NeoChiri Apr 27 '16 at 10:25
  • @nadir seems to be right... follow the steps and let us know, also check duplicated question, a NPE just need to be localized.... and finally please **tell your teacher in Spanish corporative-life we write code in english...** – Jordi Castilla Apr 27 '16 at 10:53

1 Answers1

4

You are executing the database query before binding the values

PreparedStatement  sqlAddArtist=conexion.getConnection().prepareStatement("INSERT into artist values(?,?)");
        ResultSet resultado=sqlAddArtist.executeQuery();
        while(resultado.next()){
            sqlAddArtist.setString(1, artistaVO.getNombreArtista());
            sqlAddArtist.setInt(2, getMaxId()+1);
        }

This should look like this:

PreparedStatement  sqlAddArtist=conexion.getConnection().prepareStatement("INSERT into artist values(?,?)");
sqlAddArtist.setString(1, artistaVO.getNombreArtista());
sqlAddArtist.setInt(2, getMaxId()+1);
sqlAddArtist.execute();
Nadir
  • 1,799
  • 12
  • 20