0

When I try to connect my application with MySQL, an exception is thrown: java.lang.NullPointerException.

The application then starts without a database. I debugged the program and the error is in: md.addRow(a).

The code is:

    package inmobiliaria;

    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import java.awt.Point;

    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.border.EmptyBorder;
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;
    import javax.swing.JSlider;
    import javax.swing.JTextField;
    import javax.swing.JLabel;
    import javax.swing.RowFilter;
    import javax.swing.RowSorter;
    import javax.swing.SwingConstants;
    import javax.swing.JComboBox;
    import javax.swing.DefaultComboBoxModel;

    import java.awt.Font;

    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JMenuBar;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JButton;

    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;

    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableModel;
    import javax.swing.table.TableRowSorter;

    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.KeyAdapter;

    import javax.swing.JFormattedTextField;

    import java.awt.Component;

    import javax.swing.Box;
    import javax.swing.JRadioButton;

    import java.awt.Toolkit;
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.Vector;

    public class Ventana extends JFrame {

private JPanel contentPane;
private JTextField txtNumero;
private JTextField txtNombreDelInquilino;
private JTextField txtNombreDelPropietario;
private JTextField txtDomicilio;
private JTextField txtCantidad;
private JTextArea taObservacionesDos;
private JTable table;
DefaultTableModel md;
String dataaa[][] = {};
String columnasss[] = {"NUMERO", "FECHA DE ENTRADA", "FECHA DE VENCIMIENTO", "NOMBRE DEL INQUILINO", "NOMBRE DEL PROPIETARIO", "DOMICILIO", "CANTIDAD", "OBSERVACIONES"};
private JTextField txtFiltro;
private TableRowSorter<TableModel> trsfiltro;

private Connection connect = null;
private Statement statement = null;


                            //Autor Martìn Sànchez
                            //FACEBOOK: http://www.facebook.com/martin98sanchez
    public void run() {
            try {
                Ventana frame = new Ventana();
                frame.setVisible(true);
                frame.setLocationRelativeTo(null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
/**
 * Create the frame.
 */
public Ventana() {
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
   JOptionPane.showMessageDialog(null, e.getMessage());
        return;
    }

    try {
        connect = DriverManager.getConnection("jdbc:mysql://127.0.0.1/inmobiliaria", "root", "");
    } catch (SQLException e) {
        JOptionPane.showMessageDialog(null, e.getMessage());
    return;
    }

    try {
        ResultSet rs = connect.getMetaData().getCatalogs();

    } catch (SQLException e) { }

    try {
        statement = connect.createStatement();
        ResultSet rs = statement.executeQuery("SELECT * FROM usuarios");

        // get columns info
        ResultSetMetaData rsmd = rs.getMetaData();
        int columnCount = rsmd.getColumnCount();





        // add rows to table
        while (rs.next()) {
            String[] a = new String[columnCount];
            for(int i = 0; i < columnCount; i++) {
                a[i] = rs.getString(i+1);
            }
        md.addRow(a);
        }

        // Close ResultSet and Statement
        rs.close();
        statement.close();
    } catch (Exception ex) { 
        JOptionPane.showMessageDialog(this, ex, ex.getMessage(), WIDTH, null);
    }

    setTitle("Inmobiliaria");
    //setIconImage(Toolkit.getDefaultToolkit().getImage(Ventana.class.getResource("/imagenes/inmobiliaria.png")));
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 1325, 727);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);


    txtNumero = new JTextField();
    txtNumero.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(KeyEvent e) {
            if (!Character.isDigit(e.getKeyChar())){
                e.consume();
            }
        }
    });
    txtNumero.setBounds(88, 26, 86, 20);
    contentPane.add(txtNumero);
    txtNumero.setColumns(10);

    JLabel lblNumero = new JLabel("N\u00FAmero");
    lblNumero.setBounds(22, 23, 56, 26);
    contentPane.add(lblNumero);

    JLabel lblFechaDeEntregaUno = new JLabel("Fecha de");
    lblFechaDeEntregaUno.setHorizontalAlignment(SwingConstants.CENTER);
    lblFechaDeEntregaUno.setBounds(22, 60, 56, 26);
    contentPane.add(lblFechaDeEntregaUno);

    JLabel lblFechaDeEntregaDos = new JLabel("ENTREGA");
    lblFechaDeEntregaDos.setHorizontalAlignment(SwingConstants.CENTER);
    lblFechaDeEntregaDos.setBounds(22, 82, 56, 14);
    contentPane.add(lblFechaDeEntregaDos);

    JComboBox cbDiaE = new JComboBox();
    cbDiaE.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"}));
    cbDiaE.setBounds(98, 66, 50, 20);
    contentPane.add(cbDiaE);

    JComboBox cbMesE = new JComboBox();
    cbMesE.setModel(new DefaultComboBoxModel(new String[] {"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Setiembre", "Octubre", "Noviembre", "Diciembre"}));
    cbMesE.setBounds(158, 66, 76, 20);
    contentPane.add(cbMesE);

    JComboBox cbAnioE = new JComboBox();
    cbAnioE.setModel(new DefaultComboBoxModel(new String[] {"2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023", "2024", "2025", "2026", "2027", "2028", "2029", "2030"}));
    cbAnioE.setBounds(244, 66, 56, 20);
    contentPane.add(cbAnioE);

    JLabel lblFechaDeVencimientoUno = new JLabel("Fecha de");
    lblFechaDeVencimientoUno.setHorizontalAlignment(SwingConstants.CENTER);
    lblFechaDeVencimientoUno.setBounds(22, 107, 56, 26);
    contentPane.add(lblFechaDeVencimientoUno);

    JLabel lblFechaDeVencimientoDos = new JLabel("VENCIMIENTO");
    lblFechaDeVencimientoDos.setHorizontalAlignment(SwingConstants.CENTER);
    lblFechaDeVencimientoDos.setBounds(22, 129, 76, 14);
    contentPane.add(lblFechaDeVencimientoDos);

    JComboBox cbDiaV = new JComboBox();
    cbDiaV.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"}));
    cbDiaV.setBounds(98, 113, 50, 20);
    contentPane.add(cbDiaV);

    JComboBox cbMesV = new JComboBox();
    cbMesV.setModel(new DefaultComboBoxModel(new String[] {"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Setiembre", "Octubre", "Noviembre", "Diciembre"}));
    cbMesV.setBounds(158, 113, 76, 20);
    contentPane.add(cbMesV);

    JComboBox cbAnioV = new JComboBox();
    cbAnioV.setModel(new DefaultComboBoxModel(new String[] {"2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023", "2024", "2025", "2026", "2027", "2028", "2029", "2030"}));
    cbAnioV.setBounds(244, 113, 56, 20);
    contentPane.add(cbAnioV);

    JLabel lblNombreDelInquilino = new JLabel("Nombre del Inquilino");
    lblNombreDelInquilino.setBounds(22, 154, 109, 14);
    contentPane.add(lblNombreDelInquilino);

    JLabel lblNombreDelPropietario = new JLabel("Nombre del Propietario");
    lblNombreDelPropietario.setBounds(22, 189, 137, 14);
    contentPane.add(lblNombreDelPropietario);

    txtNombreDelInquilino = new JTextField();
    txtNombreDelInquilino.setBounds(158, 151, 130, 20);
    contentPane.add(txtNombreDelInquilino);
    txtNombreDelInquilino.setColumns(10);

    txtNombreDelPropietario = new JTextField();
    txtNombreDelPropietario.setBounds(158, 186, 129, 20);
    contentPane.add(txtNombreDelPropietario);
    txtNombreDelPropietario.setColumns(10);

    JLabel lblDomicilio = new JLabel("Domicilio");
    lblDomicilio.setBounds(22, 224, 76, 14);
    contentPane.add(lblDomicilio);

    txtDomicilio = new JTextField();
    txtDomicilio.setBounds(100, 221, 200, 20);
    contentPane.add(txtDomicilio);
    txtDomicilio.setColumns(10);

    JLabel lblCantidad = new JLabel("Cantidad");
    lblCantidad.setBounds(22, 255, 76, 14);
    contentPane.add(lblCantidad);

    txtCantidad = new JTextField();
    txtCantidad.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(KeyEvent e) {
            if (!Character.isDigit(e.getKeyChar())){
                //... no lo escribe
            e.consume();
            }
        }
    });
    txtCantidad.setBounds(100, 252, 200, 20);
    contentPane.add(txtCantidad);
    txtCantidad.setColumns(10);

    JLabel lblObservaciones = new JLabel("Observaciones");
    lblObservaciones.setBounds(22, 280, 86, 14);
    contentPane.add(lblObservaciones);

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(110, 283, 204, 132);
    contentPane.add(scrollPane);

    JTextArea taObservaciones = new JTextArea();
    scrollPane.setViewportView(taObservaciones);

    JButton btnAceptar = new JButton("Aceptar");
    btnAceptar.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            String numero = txtNumero.getText();
            String nombreInquilino = txtNombreDelInquilino.getText();
            String nombrePropietario = txtNombreDelPropietario.getText();
            String domicilio = txtDomicilio.getText();
            String cantidad = txtCantidad.getText();
            String observaciones = taObservaciones.getText();
            String dDE = cbDiaE.getSelectedItem().toString();
            String mDE = cbMesE.getSelectedItem().toString();
            String aDE = cbAnioE.getSelectedItem().toString();
            String dDV = cbDiaV.getSelectedItem().toString();
            String mDV = cbMesV.getSelectedItem().toString();
            String aDV = cbAnioV.getSelectedItem().toString();
            String fechaEntrada;
            String fechaVencimiento;


            fechaEntrada = dDE + " / " + mDE + " / " + aDE;
            fechaVencimiento = dDV + " / " + mDV + " / " + aDV;


            txtNumero.setText("");
            txtNombreDelInquilino.setText("");
            txtNombreDelPropietario.setText("");
            txtDomicilio.setText("");
            txtCantidad.setText("");
            taObservaciones.setText("");
            cbDiaE.setSelectedItem("1");
            cbMesE.setSelectedItem("Enero");
            cbDiaV.setSelectedItem("1");
            cbMesV.setSelectedItem("Enero");






        }
    });
    btnAceptar.setFont(new Font("Tahoma", Font.BOLD, 18));
    btnAceptar.setBounds(98, 446, 189, 58);
    contentPane.add(btnAceptar);
    md = new DefaultTableModel(dataaa, columnasss);

    JScrollPane scrollPane_1 = new JScrollPane();

    scrollPane_1.setBounds(344, 11, 955, 493);
    contentPane.add(scrollPane_1);

    table = new JTable();
    table.setAutoResizeMode(1);
    TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<>(md);
    table.setRowSorter(sorter);
    scrollPane_1.setViewportView(table);
    table.setToolTipText("");
    table.setModel(new DefaultTableModel(
        new Object[][] {
        },
        new String[] {
            "NUMERO", "FECHA DE ENTRADA", "FECHA DE VENCIMIENTO", "NOMBRE DEL INQUILINO", "NOMBRE DEL PROPIETARIO", "DOMICILIO", "CANTIDAD", "OBSERVACIONES"
        }
    ));
        //String observacionesDos = (String) table.getValueAt(table.getSelectedRow(), 7);
            //taObservacionesDos.setText(observacionesDos);

    table.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent me) {
            JTable table2 =(JTable) me.getSource();
            Point p = me.getPoint();
            int row = table2.rowAtPoint(p);

            String observacionesDos = table.getValueAt(row, 7).toString();
            taObservacionesDos.setText(observacionesDos);

            /*if (me.getClickCount() == 2) {
                // your valueChanged overridden method 
            }*/
        }
    });
    table.setModel(md);

    JButton btnBorrarTodo = new JButton("Borrar Todo");
    btnBorrarTodo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
        }
    });
    btnBorrarTodo.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            int respuesta = JOptionPane.showConfirmDialog(null, "¿Desea borrar todos los datos guardados?", "Borrar Todo", JOptionPane.YES_NO_OPTION);
            if (respuesta == 0){
                if(md.getRowCount() == 0){
                    JOptionPane.showMessageDialog(null, "No hay ningùn archivo para borrar.");
                }else{
                    while (md.getRowCount() > 0){
                        md.removeRow(0);
                    }
                }

            }
        }
    });
    btnBorrarTodo.setFont(new Font("Tahoma", Font.BOLD, 15));
    btnBorrarTodo.setBounds(344, 515, 293, 62);
    contentPane.add(btnBorrarTodo);

    JButton btnBorrarDatoSeleccionado = new JButton("Borrar Dato Seleccionado");
    btnBorrarDatoSeleccionado.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try{
                md.removeRow(table.getSelectedRow());
            }catch(Exception x) {
                JOptionPane.showMessageDialog(null, "No se ha seleccionado ninguna fila aùn.");
            }




        }
    });
    btnBorrarDatoSeleccionado.setFont(new Font("Tahoma", Font.BOLD, 15));
    btnBorrarDatoSeleccionado.setBounds(926, 515, 373, 62);
    contentPane.add(btnBorrarDatoSeleccionado);

    txtFiltro = new JTextField();

    txtFiltro.addKeyListener(new KeyAdapter() {
        @SuppressWarnings("unchecked")
        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode()==KeyEvent.VK_ENTER){
                trsfiltro.setRowFilter(RowFilter.regexFilter(txtFiltro.getText()));
            }
        }
    });
    txtFiltro.setBounds(158, 538, 142, 20);
    txtFiltro.addKeyListener(new KeyAdapter() {
        public void keyReleased(final KeyEvent e) {
            String cadena = (txtFiltro.getText());
            txtFiltro.setText(cadena);
            repaint();
            filtro();
            }
            });
            trsfiltro = new TableRowSorter<TableModel>(table.getModel());
            table.setRowSorter(trsfiltro);
    contentPane.add(txtFiltro);
    txtFiltro.setColumns(10);

    JLabel lblFiltro = new JLabel("Filtro : ");
    lblFiltro.setBounds(102, 541, 46, 14);
    contentPane.add(lblFiltro);

    JScrollPane scrollPane_2 = new JScrollPane();
    scrollPane_2.setBounds(10, 590, 1289, 87);
    contentPane.add(scrollPane_2);

    taObservacionesDos = new JTextArea();
    taObservacionesDos.setEditable(false);
    scrollPane_2.setViewportView(taObservacionesDos);



}


public void filtro() {
    trsfiltro.setRowFilter(RowFilter.regexFilter("(?i)"+ txtFiltro.getText()));
    }
    }
1
  • Try to attach only code directly relevant to your problem. So find the code that throws the exception and add just that snippet to your question. Then it's easier the find the problem. ;) Commented Aug 9, 2015 at 17:45

1 Answer 1

1

You are calling...

md.addRow(a);

before you initialize md...

 md = new DefaultTableModel(dataaa, columnasss);

In other words, initialize it first, then call the database and do your work. Otherwise you are trying to write to a table that doesn't exist yet.

Sign up to request clarification or add additional context in comments.

4 Comments

That's a new error. Probably your local MySQL server isn't running.
thanks, really thanks but I ask you an idiot ask, Where I must put the code?, because I'm programming since 1 month ago, and I learn by internet, and with 16 years I don't understand much
A MySQL server is not a code. It's a program that runs on some machine, in this case jdbc:mysql://127.0.0.1/inmobiliaria you told the java code that there is a MySQL server on your local machine (127.0.0.1) and that there will be a database called "inmobiliaria". You have to install a server and create that database for your code to work.
thanks I could run perfectly my app, thanks thanks thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.