Java - Ayuda con listado eclipse - base de datos

 
Vista:
sin imagen de perfil

Ayuda con listado eclipse - base de datos

Publicado por Rodrigo (2 intervenciones) el 01/12/2017 00:41:07
Hola, mi problema que necesito solucionar es el siguiente.
Tengo las siguientes 3 clases

PRIMERA CLASE: Bueno es el objeto en este caso una mascota

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.sql.Date;
 
public class Mascota {
 String nombre;
 String animal;
 Date fecha;
 String historiaclinica;
 public Mascota(String nombre, String animal, Date fecha, String historiaclinica){
	 this.nombre = nombre;
	 this.animal = animal;
	 this.fecha = fecha;
	 this.historiaclinica = historiaclinica;
 }
 
public String getNombre() {
	return nombre;
}
public void setNombre(String nombre) {
	this.nombre = nombre;
}
public String getAnimal() {
	return animal;
}
public void setAnimal(String animal) {
	this.animal = animal;
}
 
public String getHistoriaclinica() {
	return historiaclinica;
}
public void setHistoriaclinica(String historiaclinica) {
	this.historiaclinica = historiaclinica;
}
public Date getFecha() {
	return fecha;
}
public void setFecha(Date fecha) {
	this.fecha = fecha;
}
public void mostrar(){
	System.out.println(this.getNombre());
	System.out.println(this.getAnimal());
	System.out.println(this.getFecha());
	System.out.println(this.getHistoriaclinica());
}
public void desparacitar(){
	String detalle;
	String fechapractica;
}
public void vacunar(){
	String detalle;
	String fechapractica;
	String fechavencimiento;
}
public void chequear(){
	String detalle;
	String fechapractica;
}
}

SEGUNDA CLASE: ES LA BASE DE DATOS

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.sql.Connection;
 
public class BDVeterinaria
{
public static Connection conexion;
 
	public BDVeterinaria() throws SQLException
	{
 
		System.out.println("Iniciando programa.");
 
		try
		{
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e)
		{
			System.out.println("No se pudo cargar el puente JDBC-ODBC.");
			return;
		}
 
		try
		{
			conexion = DriverManager.getConnection("jdbc:mysql://localhost:3306/veterinaria integrador", "root", "");
		} catch (SQLException e)
		{
			System.out.println(e);
 
		}
		System.out.println("Conexion realizada.");
	}
 
 
	public void almacenarMascota(Mascota mascota) throws SQLException
	{
		String nombre = mascota.getNombre();
		String animal = mascota.getAnimal();
		String historiaclinica = mascota.getHistoriaclinica();
		Date fecha = mascota.getFecha();
 
		PreparedStatement agregar = conexion
				.prepareStatement("INSERT INTO mascotas (nombre,animal,fecha,historiaclinica) VALUES (?,?,?,?)");
 
		agregar.setString(1, nombre);
		agregar.setString(2, animal);
		agregar.setDate(3, fecha);
		agregar.setString(4, historiaclinica);
		agregar.executeUpdate();
	}
 
 
	public static ArrayList<String> recuperarMascota() throws SQLException
	{ArrayList<String> listaM = new ArrayList<String>();
	String pedido="SELECT * FROM mascotas";
		Statement sentencia = conexion.createStatement();
		ResultSet resultado = sentencia.executeQuery(pedido);
		while (resultado.next())
		{
			listaM.add(resultado.getString("nombre"));
		}
		return listaM;
	}
 
}

TERCERA CLASE: Es la interfaz

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import javax.swing.JComboBox;
 
public class VeterinariaInterfaz extends JFrame {
	public JTextArea txtLista;
	public JComboBox<ArrayList<String>> cmbBox;
	private JPanel contentPane;
	static Connection conexion;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					VeterinariaInterfaz frame = new VeterinariaInterfaz();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
 
	/**
	 * Create the frame.
	 */
	public VeterinariaInterfaz() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
 
		JButton btnMostrar = new JButton("Mostrar Lista");
 
		btnMostrar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				cargar();
			}
		});
		btnMostrar.setBounds(10, 58, 89, 23);
		contentPane.add(btnMostrar);
 
		this.txtLista = new JTextArea();
		txtLista.setBounds(20, 92, 57, 103);
		contentPane.add(txtLista);
 
		this.cmbBox = new JComboBox();
		cmbBox.setBounds(118, 120, 129, 97);
		contentPane.add(cmbBox);
	}
	void cargar(){
		cmbBox.removeAllItems();
		ArrayList<String> listaM = new ArrayList<String>();
		try {
			listaM = BDVeterinaria.recuperarMascota();
			cmbBox.addItem(listaM);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

PROBLEMA:
La idea es que al presionar el boton de la interfaz en el combobox me muestre un listado de los nombres de las mascotas. Cuando lo hago me aparece esto:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at BDVeterinaria.recuperarMascota(BDVeterinaria.java:63)
at VeterinariaInterfaz.cargar(VeterinariaInterfaz.java:68)
at VeterinariaInterfaz$2.actionPerformed(VeterinariaInterfaz.java:50)
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$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.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$JavaSecurityAccessImpl.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)
La verdad casi ni se programar y no se que son estas cosas, pero tengo que realizarlo y la mayoria de los resultados en internet estan en ingles, que teniendo en cuenta que ya me cuesta entender en español se me hace imposible saber la solucion. Gracias
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de kingk
Val: 247
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

Ayuda con listado eclipse - base de datos

Publicado por kingk (108 intervenciones) el 05/12/2017 20:50:11
El error esta en el método cargar. Ya que utilizas el método recuperarMascota()
En el cual utilizas el objeto connection sin inicializar.La conexión se inicializa en el constructor de la clase BDVeterinaria.En la clase BDVeterinaria cambia el método recuperar mascota así
public ArrayList<String> recuperarMascota(){…

Y en el método cargar de la clase VeterinariaInterfaz cambias la parte donde agrega el listado así:
listaM=new BDVeterinaria().recuperarMascota();
cmbBox.addItem(listan);
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar