NullPointer Exception Help

1

Before the data goes to the bank I have a nullpointer that I've debugged and I can not find where the problem is. Below my classes:

package br.com.pokemax.controle;

import java.io.Serializable;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import br.com.pokemax.modelo.Habilidade;
import br.com.pokemax.negocio.HabilidadeDAO;

@ViewScoped
@ManagedBean(name = "habilidademb")
public class ControleHabilidade implements Serializable {

    private static final long serialVersionUID = 1L;

    @Inject
    private Logger log;
    private Habilidade habilidade;
    private HabilidadeDAO dao;

    private Boolean habilidadeHidden;

    public Habilidade getHabilidade() {
        return habilidade;
    }

    public void setHabilidade(Habilidade habilidade) {
        this.habilidade = habilidade;
    }

    public Boolean getHabilidadeHidden() {
        return habilidadeHidden;
    }

    public void setHabilidadeHidden(Boolean habilidadeHidden) {
        this.habilidadeHidden = habilidadeHidden;
    }

    @PostConstruct
    public void novo() {
        habilidade = new Habilidade();
    }

    public void gravar() {
        FacesMessage facesMsg;
        try {
            if (habilidade.getId() == null) {
                dao.insert(habilidade);
                facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Gravação realizada com sucesso!", "");
                FacesContext.getCurrentInstance().addMessage("messagePanel", facesMsg);
            } else {
                habilidade = dao.update(habilidade);
                facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Registro Atualizado com sucesso!", "");
                FacesContext.getCurrentInstance().addMessage("messagePanel", facesMsg);
            }

        } catch (Exception e) {
            facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro:" + e.getMessage(), "");
            FacesContext.getCurrentInstance().addMessage("messagePanel", facesMsg);
            log.warning("Erro: " + e.getMessage());
            return;
        }
    }

}

Template:

package br.com.pokemax.modelo;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.NotBlank;

@Entity
@Table(name="tb_habilidade")
public class Habilidade implements Serializable{


    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank
    @Column(length=20,nullable=false)
    private String nome;

    @NotNull
    @Column(length=150,nullable=false)
    private String descricao;

    @Column(name="efeito_secundario")
    private String efeitoSecundario;


    public Habilidade() {
    }



    public Habilidade(String nome, String descricao, String efeitoSecundario) {
        super();
        this.nome = nome;
        this.descricao = descricao;
        this.efeitoSecundario = efeitoSecundario;
    }


    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }


    public String getEfeitoSecundario() {
        return efeitoSecundario;
    }


    public void setEfeitoSecundario(String efeitoSecundario) {
        this.efeitoSecundario = efeitoSecundario;
    }


    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }



    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((descricao == null) ? 0 : descricao.hashCode());
        result = prime * result + ((efeitoSecundario == null) ? 0 : efeitoSecundario.hashCode());
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result + ((nome == null) ? 0 : nome.hashCode());
        return result;
    }



    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Habilidade other = (Habilidade) obj;
        if (descricao == null) {
            if (other.descricao != null)
                return false;
        } else if (!descricao.equals(other.descricao))
            return false;
        if (efeitoSecundario == null) {
            if (other.efeitoSecundario != null)
                return false;
        } else if (!efeitoSecundario.equals(other.efeitoSecundario))
            return false;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        if (nome == null) {
            if (other.nome != null)
                return false;
        } else if (!nome.equals(other.nome))
            return false;
        return true;
    }




}

DAO:

package br.com.pokemax.negocio;

import java.util.List;
import java.util.logging.Logger;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;

import br.com.pokemax.modelo.Habilidade;

@Stateless
@LocalBean  
public class HabilidadeDAO implements DAO<Habilidade,String>{

    @Inject
    private EntityManager em;

    @Inject
    private Logger log;


    @Override
    public Habilidade insert(Habilidade t) throws Exception {
        log.info("Persistindo " + t);
        em.persist(t);
        return t;
    }

    @Override
    public Habilidade update(Habilidade t) throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Habilidade delete(Habilidade t) throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Habilidade find(String k) throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<Habilidade> findAll() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

}

xhtml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:p="http://primefaces.org/ui">
<ui:composition template="/layout/template.xhtml">
    <ui:define name="content">
        <h:form>
            <p:panel header="Cadastrando Habilidades">
                <p:messages />
                <h:panelGrid id="cadastro" columns="3">
                    <h:outputLabel value="Nome: " />
                    <p:inputText id="nome" value="#{habilidademb.habilidade.nome}" size="20" />
                    <p:message for="nome" />
                    <h:outputLabel value="Descrição: " rendered="true" />
                    <p:inputTextarea id="descricao"
                        value="#{habilidademb.habilidade.descricao}" rows="6" cols="20" />
                    <p:message for="descricao" />
                    <h:outputLabel id="efeitoS" value="Possui efeito secundário? : " />
                    <p:selectBooleanButton id="efeito"
                        value="#{habilidademb.habilidadeHidden}" onLabel="Sim"
                        offLabel="Não" style="width:60px" />
                    <p:message for="efeito" />
                    <h:outputLabel value="Efeito Secundário: "
                        rendered="#{habilidademb.habilidadeHidden == true}" />
                    <p:inputTextarea id="secundario"
                        value="#{habilidademb.habilidade.efeitoSecundario}" rows="6"
                        cols="20" rendered="#{habilidademb.habilidadeHidden == true}" />
                    <p:message for="secundario" />
                    <p:commandButton action="#{habilidademb.gravar}" value="Salvar" update="cadastro"/>
                </h:panelGrid>
            </p:panel>
        </h:form>
    </ui:define>
</ui:composition>
</html>

Useful Class:

package br.com.pokemax.util;

import java.util.logging.Logger;

import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;


public class JPAUtil {

    @Produces
    @PersistenceContext
    EntityManager em;

    @Produces
    public Logger produceLog(InjectionPoint injectionPoint) {
        return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
    }

}

I'm trying to debug this case further, I noticed that when it arrives in the DAO class, it reads the line:

log.info("Persistindo " + t);

Then it already falls in catch . The error shown in the console is:

  

13: 33: 20,806 WARNING [br.com.pokemax.controls.Controllability] (default task-8) Error: null

    
asked by anonymous 04.06.2016 / 17:58

2 answers

0

I discovered what it was, looking at the debug, I noticed that the dao was null, so I used the Injection instead of instantiating it, so it worked.

@Inject
HabilidadeDAO dao;
    
04.06.2016 / 20:34
4

I do not know if it's enough but something you can solve is to change this line:

private HabilidadeDAO dao = new HabilidadeDAO();

For more help you would need more context.

The code was accessing the property without initializing it. This does the initialization. If it's the right way to do it I do not know, it depends on your code.

After editing, the same problem occurs in the em variable and must be solved in the same way. This will happen with all uninitialized variables. So I suggest learning about how variables work is a pretty basic concept, before trying to do anything more complex. While not mastering this, it will only be filling gaps and not really programming.

The purpose of the website is not to play the mistakes for others to correct, it is to resolve doubts that can help everyone. In addition the problem of the question has been solved, it is no use to keep editing and putting new identical errors. Nor do I find it appropriate to ask a question for every null reference error that appears in the code. To tell you the truth I consider this question duplicated from several others that have already been answered before about the same thing. The problem is recurring because people do not learn the basics. Most are duplicate .

I have not even talked about exceptions used the wrong way because it is not in the scope of the question and is a more complex subject. I leave a list of questions that can help , but I know no one reads and keeps doing it wrong.

    
04.06.2016 / 18:01