java.lang.NullPointerException in method [closed]

1
package view;

import br.com.genius.dal.ModuloConexao;
import java.sql.*;
import java.util.ArrayList;
import javax.swing.JOptionPane;

public class Chamada_ListaCompra extends javax.swing.JInternalFrame {

    Connection conexao = null;
    PreparedStatement pst = null;
    ResultSet rs = null;
    ArrayList id = new ArrayList();

    public Chamada_ListaCompra(ArrayList Id) {
        initComponents();
        id = Id;
    }

    //esse é o método

38  public void setar(ArrayList Ident) {
39      int tam = Ident.size();
40      int i;
41      String periodo = "M";
42      if (cmbPeriodo.getSelectedItem().equals("Semanal (S)")) {
43          periodo = "S";
44      } else if (cmbPeriodo.getSelectedItem().equals("Quinzenal (Q)")) {
45          periodo = "Q";
46      }
47      String sql = "UPDATE 'genius'.'produtos' SET 'fornecedor_principal'= ?, 'Periodicidade'= ? WHERE 'Id'= ?";
48      for (i=0; i<tam; i++) {
49          try {
50              String n = Ident.get(i).toString();
51              String f = txtFornecedor.getText();
52              pst = conexao.prepareStatement(sql);
53              pst.setString(1, f);
54              pst.setString(2, periodo);
55              pst.setString(3, n);
56              pst.executeUpdate();
57              System.out.println("Produto de id = " + n + " Alterado --> Fornecedor = " + txtFornecedor.getText() + " / Periodicidade = " + periodo);
58              dispose();
59          } catch (Exception e) {
60              JOptionPane.showMessageDialog(null, "Erro");
                System.out.println(e);
            }
        }

    }
}

When I run the following error appears:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at view.Chamada_ListaCompra.setar(Chamada_ListaCompra.java:52)
at view.Chamada_ListaCompra.btnOkActionPerformed(Chamada_ListaCompra.java:182)
at view.Chamada_ListaCompra.access$000(Chamada_ListaCompra.java:19)
at view.Chamada_ListaCompra$1.actionPerformed(Chamada_ListaCompra.java:103)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6535)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6300)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4891)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
CONSTRUÍDO COM SUCESSO (tempo total: 18 segundos)

But when I change this part:

for (i=0; i<tam; i++) {
            try {
                String n = Ident.get(i).toString();
                String f = txtFornecedor.getText();
                pst = conexao.prepareStatement(sql);
                pst.setString(1, f);
                pst.setString(2, periodo);
                pst.setString(3, n);
                pst.executeUpdate();
                System.out.println("Produto de id = " + n + " Alterado --> Fornecedor = " + txtFornecedor.getText() + " / Periodicidade = " + periodo);
                dispose();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "Erro");
                System.out.println(e);
            }

For this:

for (i=0; i<tam; i++) {
            try {
                String n = Ident.get(i).toString();
                String f = txtFornecedor.getText();
                System.out.println("Produto de id = " + n + " Alterado --> Fornecedor = " + txtFornecedor.getText() + " / Periodicidade = " + periodo);
                dispose();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "Erro");
                System.out.println(e);
            }

It runs normally and prints:

Produto de id = 3 Alterado --> Fornecedor = teste / Periodicidade = M
Produto de id = 5 Alterado --> Fornecedor = teste / Periodicidade = M
Produto de id = 7 Alterado --> Fornecedor = teste / Periodicidade = M
Produto de id = 8 Alterado --> Fornecedor = teste / Periodicidade = M
Produto de id = 9 Alterado --> Fornecedor = teste / Periodicidade = M
Produto de id = 11 Alterado --> Fornecedor = teste / Periodicidade = M

Does anyone know the problem?

    
asked by anonymous 28.09.2016 / 16:02

1 answer

1

The error is therefore in line 52 , you try to use an object that has not yet been initialized!

Here is an example of how to initialize Connection :

Connection getConnection() { 
    String DB_CONN_STRING = "jdbc:mysql://localhost:3306/data_base_name”;

    String DRIVER_CLASS_NAME = "org.com.Seu.Driver”;
    String USER_NAME = “usuario”;
    String PASSWORD = “senha”;

    Connection result = null;
    try {
       Class.forName(DRIVER_CLASS_NAME).newInstance();
    }
    catch (Exception ex){
      System.out.println("Não foi possível carregar o driver: " + DRIVER_CLASS_NAME);
    }

    try {
      result = DriverManager.getConnection(DB_CONN_STRING, USER_NAME, PASSWORD);
    }
    catch (SQLException e){
      System.out.println( "Driver lcarregado, mas não foi possíve conectar: " + DB_CONN_STRING);
    }
    return result;
  }

Then before using the connection object, initialize:

conexao = getConnection();
 pst = conexao.prepareStatement(sql);
    
28.09.2016 / 18:49