Problemas na Tela Listar Cliente

Boa noite, Galera

estou com o seguinte problema na tela Listar Cliente, só consigo listar pelo código, preciso que liste também pelo nome do cliente.

Segue o código

[code]public List<cliente_locadora> buscarClientePorParametros(Integer cod_cli, String nome_cli) {
EntityManager em = JpaUtil.getEntityManager();

	List<cliente_locadora> cliente = new ArrayList<cliente_locadora>();

	StringBuilder jpql = new StringBuilder("SELECT p FROM cliente_locadora p WHERE p.cod_cli IS NOT NULL");

	if (cod_cli != null && !cod_cli.equals("")) {
		jpql.append(" AND p.cod_cli = " + cod_cli);
	}

	if (nome_cli != null && !nome_cli.equals("")) {
		jpql.append(" AND p.nome_cli LIKE '%" + nome_cli + "%'");
	}

	try {
		Query query = em.createQuery(jpql.toString());
		cliente = query.getResultList();
	} catch (Exception e) {
		e.printStackTrace();
	}

	return cliente;
}

[/code]

O que devo fazer?

O erro que gera é o seguinte:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
	at java.lang.NumberFormatException.forInputString(Unknown Source)
	at java.lang.Integer.parseInt(Unknown Source)
	at java.lang.Integer.parseInt(Unknown Source)
	at views.BuscaCliente.buscarAction(BuscaCliente.java:251)
	at views.BuscaCliente.access$4(BuscaCliente.java:247)
	at views.BuscaCliente$5.actionPerformed(BuscaCliente.java:239)
	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.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)

você nao consegue usar AND no seu select ?

para o código funciona, mas para o nome não consigo fazer funcionar

StringBuilder jpql = new StringBuilder("SELECT p FROM cliente_locadora p WHERE p.cod_cli IS NOT NULL");   //esta assim

StringBuilder jpql = new StringBuilder("SELECT p FROM cliente_locadora p WHERE p.cod_cli IS NOT NULL AND nomedocliente LIKE ?");  //onde o ? eh o valor da variavel nome_cli

Colokei AND porque voce quer o NOT NULL e o nome do Cliente

Caso queira um ou outro troque o AND por OR

Abraços.

xD~~

[b]O erro continua o mesmo. Alguma outra idéia?

Desde já agradeço a todos;

Qual o Erro, posta pra gente!

xD~~

O erro é esse


Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
	at java.lang.NumberFormatException.forInputString(Unknown Source)
	at java.lang.Integer.parseInt(Unknown Source)
	at java.lang.Integer.parseInt(Unknown Source)
	at views.BuscaCliente.buscarAction(BuscaCliente.java:251)
	at views.BuscaCliente.access$4(BuscaCliente.java:247)
	at views.BuscaCliente$5.actionPerformed(BuscaCliente.java:239)
	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.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)

Dá uma olhada como o código ficou:

public List<cliente_locadora> buscarClientePorParametros(Integer cod_cli, String nome_cli) {
		EntityManager em = JpaUtil.getEntityManager();

		List<cliente_locadora> cliente = new ArrayList<cliente_locadora>();

		StringBuilder jpql = new StringBuilder("SELECT p FROM cliente_locadora p WHERE p.cod_cli IS NOT NULL OR nome_cli LIKE '%" + nome_cli + "%'");  //onde o ? eh o valor da variavel nome_cli  
		if (cod_cli != null && !cod_cli.equals("")) {
			jpql.append(" AND p.cod_cli = " + cod_cli);
		}

		if (nome_cli != null && !nome_cli.equals("")) {
			jpql.append(" AND p.nome_cli LIKE '%" + nome_cli + "%'");
		}

		try {
			Query query = em.createQuery(jpql.toString());
			cliente = query.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return cliente;
	}

Bemm…

Esta dando de NumberFormatException

Seria Erro na hora de Converter o Numeroo!

como vc faz para passar o Integer para String ou a String para Integer??

Pode postar a parte que faz isso??

xD~~

vou te passar a tela inteira


package views;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;

import Beans.cliente_locadora;
import Conexao.JpaUtil;



@SuppressWarnings("serial")
public class BuscaCliente extends JFrame {

	private JButton buscarButton;
	private JScrollPane scrollPane;
	private JButton excluirButton;
	private JButton editarButton;
	private JButton visualizarButton;
	private JButton fecharButton;
	private JSeparator separator;
	private JLabel clienteLabel;
	private JLabel nomeLabel;
	private JLabel codigoLabel;
	private JTable tabela;
	private JTextField nomeField;
	private JTextField codigoField;

	class TableModelCliente extends AbstractTableModel {
		private static final long serialVersionUID = 1L;

		private List<cliente_locadora> cliente_locadora;
		private String[] colunas = { "Código", "Nome", "Telefone" };
		private int colSize[] = { 50, 80, 210};

		public int getColumnCount() {
			return colunas.length;
		}

		public int getRowCount() {
			if (cliente_locadora == null) {
				return 0;
			}

			return cliente_locadora.size();
		}

		public Object getValueAt(int rowIndex, int columnIndex) {
			cliente_locadora cliente = cliente_locadora.get(rowIndex);

			switch (columnIndex) {
			case 0:
				return cliente.getCod_cli();
			case 1:
				return cliente.getNome_cli();
			case 2:
				return cliente.getFone_residencial();
			default:
				return null;
			}
		}

		public Class<?> getColumnClass(int columnIndex) {
			if (columnIndex == 2) {
				if (cliente_locadora != null && !cliente_locadora.isEmpty()) {
					return getValueAt(0, columnIndex).getClass();
				}
			}

			return super.getColumnClass(columnIndex);
		}

		@Override
		public String getColumnName(int column) {
			return colunas[column];
		}

		public void setColumnsWidth() {
			for (int i = 0; i < colSize.length; i++) {
				TableColumn tableColumn = tabela.getColumnModel().getColumn(i);
				tableColumn.setPreferredWidth(colSize[i]);
				tableColumn.setMinWidth(colSize[i]);
			}
		}

		public void addItem(cliente_locadora cliente) {
			if (cliente_locadora == null) {
				cliente_locadora = new ArrayList<cliente_locadora>();
			}

			cliente_locadora.add(cliente);

			tabela.updateUI();
		}

		public cliente_locadora getItem(int index) {
			return cliente_locadora.get(index);
		}

		public void setItems(List<cliente_locadora> list) {
			cliente_locadora = list;

			tabela.updateUI();
		}

		public List<cliente_locadora> getItems() {
			return cliente_locadora;
		}

		public void removeItem(int index) {
			if (cliente_locadora != null) {
				cliente_locadora.remove(index);
			}

			tabela.updateUI();
		}

		public void removeItem(Object o) {
			if (cliente_locadora != null) {
				cliente_locadora.remove(o);
			}

			tabela.updateUI();
		}

		public void removeAll() {
			cliente_locadora = null;

			tabela.updateUI();
		}
	}

	public BuscaCliente() {
		super();
		getContentPane().setBackground(Color.WHITE);
		setTitle("Busca de Clientes");
		getContentPane().setLayout(null);
		setBounds(100, 100, 451, 352);

		codigoLabel = new JLabel();
		codigoLabel.setText("Código:");
		codigoLabel.setBounds(10, 10, 88, 14);
		getContentPane().add(codigoLabel);

		codigoField = new JTextField();
		codigoField.setBounds(10, 25, 88, 20);
		getContentPane().add(codigoField);

		nomeLabel = new JLabel();
		nomeLabel.setText("Nome:");
		nomeLabel.setBounds(104, 10, 241, 14);
		getContentPane().add(nomeLabel);

		nomeField = new JTextField();
		nomeField.setBounds(104, 25, 241, 20);
		getContentPane().add(nomeField);

		clienteLabel = new JLabel();
		clienteLabel.setText("Clientes");
		clienteLabel.setBounds(10, 63, 69, 14);
		getContentPane().add(clienteLabel);

		separator = new JSeparator();
		separator.setBounds(70, 70, 363, 2);
		getContentPane().add(separator);

		scrollPane = new JScrollPane();
		scrollPane.setBackground(Color.WHITE);
		scrollPane.setBounds(10, 83, 423, 196);
		getContentPane().add(scrollPane);

		tabela = new JTable();
		tabela.setModel(new TableModelCliente());
		TableModelCliente tmb = (TableModelCliente) tabela.getModel();
		tmb.setColumnsWidth();
		scrollPane.setViewportView(tabela);

		fecharButton = new JButton();
		fecharButton.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				dispose();
			}
		});
		fecharButton.setText("Fechar");
		fecharButton.setBounds(340, 285, 93, 23);
		getContentPane().add(fecharButton);

		visualizarButton = new JButton();
		visualizarButton.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				visualizarAction();
			}
		});
		visualizarButton.setText("Visualizar");
		visualizarButton.setBounds(241, 285, 93, 23);
		getContentPane().add(visualizarButton);

		editarButton = new JButton();
		editarButton.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				editarAction();
			}
		});
		editarButton.setText("Editar");
		editarButton.setBounds(142, 285, 93, 23);
		getContentPane().add(editarButton);

		excluirButton = new JButton();
		excluirButton.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				excluirAction();
			}
		});
		excluirButton.setText("Excluir");
		excluirButton.setBounds(43, 285, 93, 23);
		getContentPane().add(excluirButton);

		buscarButton = new JButton();
		buscarButton.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				buscarAction();
			}
		});
		buscarButton.setText("Buscar");
		buscarButton.setBounds(351, 24, 82, 23);
		getContentPane().add(buscarButton);
	}

	private void buscarAction() {
		TableModelCliente modelCliente = (TableModelCliente) tabela.getModel();
		modelCliente.removeAll();

		List<cliente_locadora> cliente_locadora = buscarClientePorParametros(Integer.parseInt(codigoField.getText()), nomeField.getText());

		if (cliente_locadora != null && !cliente_locadora.isEmpty()) {
			modelCliente.setItems(cliente_locadora);
			tabela.setRowSelectionInterval(0, 0);
			tabela.requestFocus();
		} else {
			codigoField.requestFocus();
		}
	}

	@SuppressWarnings("unchecked")
	public List<cliente_locadora> buscarClientePorParametros(Integer cod_cli, String nome_cli) {
		EntityManager em = JpaUtil.getEntityManager();

		List<cliente_locadora> cliente = new ArrayList<cliente_locadora>();

		StringBuilder jpql = new StringBuilder("SELECT p FROM cliente_locadora p WHERE p.cod_cli IS NOT NULL OR nome_cli LIKE '%" + nome_cli + "%'");  //onde o ? eh o valor da variavel nome_cli  
		if (cod_cli != null && !cod_cli.equals("")) {
			jpql.append(" AND p.cod_cli = " + cod_cli);
		}

		if (nome_cli != null && !nome_cli.equals("")) {
			jpql.append(" AND p.nome_cli LIKE '%" + nome_cli + "%'");
		}

		try {
			Query query = em.createQuery(jpql.toString());
			cliente = query.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return cliente;
	}
	
	public cliente_locadora buscarClientePorId(Integer id) {
		EntityManager em = JpaUtil.getEntityManager();

		cliente_locadora cliente = new cliente_locadora();

		StringBuilder jpql = new StringBuilder("SELECT p FROM cliente_locadora p WHERE p.cod_cli = " + id);

		try {
			Query query = em.createQuery(jpql.toString());
			cliente = (cliente_locadora) query.getSingleResult();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return cliente;
	}

	public Boolean excluir(cliente_locadora cliente) {
		EntityManager em = JpaUtil.getEntityManager();

		em.getTransaction().begin();
		try {
			em.remove(em.merge(cliente));
			em.getTransaction().commit();

			return true;
		} catch (Exception e) {
			e.printStackTrace();

			try {
				em.getTransaction().rollback();
			} catch (Exception e1) {
				return false;
			}

			return false;
		}
	}

	public static String formatDecimal(Double value) {
		if (value != null) {
			DecimalFormat formatDecimal = new DecimalFormat();
			formatDecimal.applyPattern("###,###,##0.00;(###,###,##0.00)");

			return formatDecimal.format(value);
		} else {
			return "";
		}
	}

	private void visualizarAction() {
		if (tabela.getRowCount() > 0 && tabela.getSelectedRowCount() > 0) {
			TableModelCliente modelCliente = (TableModelCliente) tabela.getModel();

			cliente_locadora cliente = modelCliente.getItem(tabela.getSelectedRow());

			try {
				JanelaCliente  gp = new JanelaCliente (JpaUtil.emf, cliente, true);
				gp.setVisible(true);
			} catch (ParseException e) {
				e.printStackTrace();
			}

		} else {
			JOptionPane.showMessageDialog(this, "Nenhum Grupo selecionado para Visualização.", "Aviso", JOptionPane.INFORMATION_MESSAGE);
		}
	}

	private void editarAction() {
		if (tabela.getRowCount() > 0 && tabela.getSelectedRowCount() > 0) {
			TableModelCliente modelCliente = (TableModelCliente) tabela.getModel();

			cliente_locadora cliente = modelCliente.getItem(tabela.getSelectedRow());
			
			try {
				JanelaCliente gp = new JanelaCliente(null, cliente, false);
			} catch (ParseException e) {
				e.printStackTrace();
			}

			List<cliente_locadora> cliente1 = buscarClientePorParametros(Integer.parseInt(codigoField.getText()), nomeField.getText());
			if (cliente1 != null && !cliente1.isEmpty()) {
				modelCliente.removeAll();

				for (cliente_locadora cliente2 : cliente1) {
					modelCliente.addItem(cliente2);
				}
			}
		} else {
			JOptionPane.showMessageDialog(this, "Nenhum Cliente selecionado para Edição.", "Aviso", JOptionPane.INFORMATION_MESSAGE);
		}
	}
	private void excluirAction() {
		if (tabela.getRowCount() > 0 && tabela.getSelectedRowCount() > 0) {

			TableModelCliente buscaCliente = (TableModelCliente) tabela.getModel();

			cliente_locadora cliente = buscaCliente.getItem(tabela.getSelectedRow());

			int opt = JOptionPane.showConfirmDialog(null, "Confirma excluir o Cliente " + cliente.getNome_cli() + "?", "Confirmação", JOptionPane.YES_NO_OPTION);
			if (opt == JOptionPane.YES_OPTION) {

				buscaCliente.removeItem(cliente);

				if (excluir(cliente)) {
					JOptionPane.showMessageDialog(this, "Cliente excluído com Sucesso.", "Sucesso", JOptionPane.INFORMATION_MESSAGE);
				} else {
					buscaCliente.addItem(cliente);
					JOptionPane.showMessageDialog(this, "Erro ao excluir Cliente.", "Erro", JOptionPane.ERROR_MESSAGE);
				}
			}
		} else {
			JOptionPane.showMessageDialog(this, "Nenhum Cliente selecionado para Exclusão.", "Aviso", JOptionPane.INFORMATION_MESSAGE);
		}
	}
}

E o erro continua sendo o mesmo ? Na mesma linha etc ?
Edit: Pois se for, o que está acontecendo é que nessa linha do seu código:

List<cliente_locadora> cliente_locadora = buscarClientePorParametros(Integer.parseInt(codigoField.getText()), nomeField.getText());

O valor de codigoField.getText() está retornando a String “” que está gerando o NumberFormatException pelo parseInt

Tenta assim:

List<cliente_locadora> cliente_locadora = buscarClientePorParametros(Integer.valueOf(codigoField.getText()), nomeField.getText()); 

Se não der certo isso tenta:

List<cliente_locadora> cliente_locadora;
cliente_locadora = buscarClientePorParametros(Integer.valueOf(codigoField.getText()), nomeField.getText()); 

ainda o problema continua, e é o mesmo erro.

Você trocou isso em todos os lugares??

O Erro é na mesma linhaa??

da um System.out.printl(Integer.valueOf(codigoField.getText());

pra ver se tah pegando um valor validoo!!

se nao substitui o Integer.valueOf(codigoField.getText()) por um numero valor, EX. 1

xD~~

falei no post anterior onde está o problema …
repetindo:
o método getText() do seu objeto codigoField está retornando a String “”
O método parseInt da classe Integer gera uma NumberFormatException quando tenta transformar essa String “” em um número.

substituindo pelo numero 1
da o seguinte erro

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2
	at sun.font.FontDesignMetrics.charsWidth(Unknown Source)
	at javax.swing.text.Utilities.getTabbedTextOffset(Unknown Source)
	at javax.swing.text.Utilities.getTabbedTextOffset(Unknown Source)
	at javax.swing.text.Utilities.getTabbedTextOffset(Unknown Source)
	at javax.swing.text.PlainView.viewToModel(Unknown Source)
	at javax.swing.text.FieldView.viewToModel(Unknown Source)
	at javax.swing.plaf.basic.BasicTextUI$RootView.viewToModel(Unknown Source)
	at javax.swing.plaf.basic.BasicTextUI.viewToModel(Unknown Source)
	at javax.swing.text.DefaultCaret.moveCaret(Unknown Source)
	at javax.swing.text.DefaultCaret.mouseDragged(Unknown Source)
	at java.awt.AWTEventMulticaster.mouseDragged(Unknown Source)
	at java.awt.Component.processMouseMotionEvent(Unknown Source)
	at javax.swing.JComponent.processMouseMotionEvent(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.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)

cronos, mas o que devo alterar?

ArrayIndexOutOfBoundsException

Issu eh qdo seu Array eh maior doq existe…

vc deve estar fazendo alguma condiçao q faça isso…

Lembre-se que um Array com 3 itens ehh…

Array 1 = posiçao 0
Array 2 = posiçao 1
Array 3 = posiçao 2

Voce deve estar pegando em algum lugar o Array 2 sendo que nao tem ele!!
Talvez tenha um ou nenhum!!

xD~~

considerando que o codeField = um JTextField, basta você preencher ele com um valor numérico válido antes de chamar a busca.
Agora tem que ver onde exatamente está dando esse próximo erro. Honestamente estou meio cansado para ficar lendo linha por linha caçando qual que está gerando o erro hehe … se der pra postar isso ajudaria

bom o valor inteiro seria nessa posiçao?

[code]
List<cliente_locadora> cliente_locadora;

	cliente_locadora = buscarClientePorParametros(1, nomeField.getText()); [/code]

Colocar o “1” pode servir como exemplo, mas após isso, que parte do código está gerando o novo erro ?