Erro nullPointerException na hora de formatar data para ser alocada no banco de dados

3 respostas
AndLobo

Boa noite a todos estou com esse erro na minha aplicação:

trecho 1

29/07/2011 21:52:40 org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet AdicionaTime threw exception
java.lang.NullPointerException
at java.util.Calendar.setTime(Calendar.java:1075)
at br.com.Projeto.servlet.AdicionaTime.doGet(AdicionaTime.java:37)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

Corresponde a esse trecho de código
package br.com.Projeto.servlet;

import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.Projeto.Dao.PfDAO;
import br.com.Projeto.bean.Time;


public class AdicionaTime extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Time time = new Time();
		time.setNome(request.getParameter("nome"));
		time.setCdRegistro(request.getParameter("CdRegistro"));
		
		SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy");
		Date dtFundacaoDate = null;
		
		try {
			dtFundacaoDate =  (Date) sf.parse(request.getParameter("dtFundacao"));  //corresponde a este trecho (2)
		} catch (Exception e) {
			e.printStackTrace();
			response.sendRedirect("/projetoFinalJspServlet/erro.jsp");
		}
		
		Calendar dtFundacaoCalendar = Calendar.getInstance();
		dtFundacaoCalendar.setTime(dtFundacaoDate);  //corresponde a este trecho (1)
		
		time.setDtFundacao(dtFundacaoCalendar);
		
		if(request.getParameter("id").isEmpty()){
			try {
				PfDAO dao = new PfDAO();
				dao.adicionaTime(time); // aqui direciona para outra classe
				response.sendRedirect("/projetoFinalJspServlet/sucesso.jsp");
			} catch (SQLException e) {
				e.printStackTrace();
				response.sendRedirect("/projetoFinalJspServlet/erro.jsp");
			}
		}
	}
	
}

E este aviso:
trecho 2
java.lang.NullPointerException
at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1235)
at java.text.DateFormat.parse(DateFormat.java:335)
at br.com.Projeto.servlet.AdicionaTime.doGet(AdicionaTime.java:30)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

package br.com.Projeto.Dao;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import br.com.Projeto.bean.Jogador;
import br.com.Projeto.bean.Time;

public class PfDAO {
  private Connection conexao;
  
    public PfDAO() throws SQLException{
    	this.conexao = new ConnectionFactory().getConnection();
    }
     public void adicionaJogador(Jogador jogador) throws SQLException{
    	 String sql = "insert into(id_jogador, codigo_registro, nome," +
    	 		" data_nascimento, id_posicao, id_time)values (?,?,?,?,?,?)";
    	 PreparedStatement stm = conexao.prepareStatement(sql);
    	 
    	 stm.setLong(1, jogador.getId());
    	 stm.setLong(2, jogador.getCdRegistro());
    	 stm.setString(3, jogador.getNome());
    	 stm.setDate(4, new Date(jogador.getDtNascimento().getTimeInMillis()));
    	 stm.setLong(5, jogador.getIdPosicao());
    	 stm.setLong(6, jogador.getIdTime());
    	 
    	 stm.execute();
    	 stm.close();
    	 conexao.close();
     }
     
     public List<Jogador> listarJogadores() throws SQLException{
    	 String sql = "select * from jogador";
    	 PreparedStatement stm = conexao.prepareStatement(sql);
    	 
    	 ResultSet rs = stm.executeQuery();
    	 
    	 List<Jogador> jogadores = new ArrayList<Jogador>();
    	 while(rs.next()){
    		 Jogador j = new Jogador();
    		 j.setId(rs.getLong("id_jogador"));
    		 j.setNome(rs.getString("nome"));
    		 
    		 Calendar data = Calendar.getInstance();
    		 data.setTime(rs.getDate("data_nascimento"));
    		 
    		 j.setIdPosicao(rs.getLong("id_posicao"));
    		 j.setIdPosicao(rs.getLong("id_time"));
    		 
    		 rs.close();
    		 stm.close();
    		 conexao.close();
    	 }  
    	 return jogadores;
     }
      
     public void adicionaTime(Time time) throws SQLException{  //vem para este trecho
    	 String sql = "insert into(id_time, codigo_registro, nome_time," +
    	 		" data_fundacao)values (?,?,?,?)";
    	 PreparedStatement stm = conexao.prepareStatement(sql);
    	 stm.setLong(1, time.getId());
    	 stm.setString(2, time.getNome());
    	 stm.setString(3, time.getCdRegistro());
    	 stm.setDate(3,new Date(time.getDtFundacao().getTimeInMillis()) );
    	
    	 stm.execute();
    	 stm.close();
    	 conexao.close();
     }
     
     public List<Time> recuperarTimes() throws SQLException{
    	 String sql = " SELECT * FROM time";
    	 PreparedStatement stm = conexao.prepareStatement(sql);
    	 
    	 ResultSet rs = stm.executeQuery();
    	 
    	 List<Time> times = new ArrayList<Time>();
    	 while (rs.next()) {
			Time t = new Time();
			t.setId(rs.getLong("id_time"));
			t.setNome(rs.getString("nome"));
			t.setCdRegistro(rs.getString("codigo_resgistro"));
			
			Calendar data = Calendar.getInstance();
			data.setTime(rs.getDate("dtFundacao"));
			
			t.setDtFundacao(data);
			times.add(t);
			
			rs.close();
			stm.close();
			conexao.close();
		}
    	 
		return times;
     }
}

c alguém puder analisar e me corrigir, pois ñ consigo pensar em mais nada, sou novato, este código ñ está terminado. Aguardo respostas. Grato

3 Respostas

Luciano_Lopes

NullPointerException ocorre quando você esta chamando algo que ainda não foi criado, dê uma olhada nesse seu AdicionaTime para ver se não esta chamando antes de cria-lo.

AndLobo

Boa noite, nestes trechos estou apenas criando uma formatador, depois estou convertendo para uma data do tipo java.util.Date, por ultimo setando a data no formato Calendar no objeto dtFundacao, bom acho q é isso.

AndLobo

Boa noite, nestes trechos estou apenas criando uma formatador, depois estou convertendo para uma data do tipo java.util.Date, por ultimo setando a data no formato Calendar no objeto dtFundacao, bom acho q é isso.

O erro tava na minha pagina jsp q estava errada<td><input type="text" value="<fmt:formatDate value='${Time.dtFndacao.time}' pattern='dd/MM/yyyy'/>" name="Data da Fundacao" size="15" maxlength="10"></td>

mas é assim<td><input type="text" value="<fmt:formatDate value='${Time.dtFndacao.time}' pattern='dd/MM/yyyy'/>" name="dtFundacao" size="15" maxlength="10"></td>

Valeu pela força
[Resolvido]

Criado 29 de julho de 2011
Ultima resposta 30 de jul. de 2011
Respostas 3
Participantes 2