Help in Nullpointer Exception

Asked

Viewed 112 times

-1

Before the data goes to the bank I’m with a nullpointer that already debugged and I can’t find where the problem is. Down with 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;
        }
    }

}

Model:

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>

Classe Util:

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 more, I noticed that when it arrives in the DAO class, it reads the line:

log.info("Persistindo " + t);

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

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

  • Where is that line?

  • @diegofm next to Try in the Control class.

  • @Douglas Did the answer solve what you were looking for? Do you think you can accept it now? If not, do you need something better? You can accept any of them, including yours.

2 answers

4

I don’t know if it’s enough but something can fix it is to change this line:

private HabilidadeDAO dao = new HabilidadeDAO();

I put in the Github for future reference.

To help more 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 don’t know, it depends on your code.

After editing the same problem occurs in the variable em and should be solved in the same way. This will happen with all uninitialized variables. So I suggest learning about the functioning of variables, which is a very basic concept, before trying to do anything more complex. Until you master it, you’re just filling in gaps and not actually programming.

The goal of the site is not to play the mistakes for others to fix, is to solve questions who can help everyone. In addition the question problem has been solved, it is no use to keep editing and putting new identical errors. I don’t even think it’s appropriate to ask a question for every mistake null Reference that appear in the code. To tell the truth I consider this question duplicated several others that have been answered before on the same thing. The problem is recurring because people don’t learn the basics. Most of them are duplicates.

I haven’t even talked about exceptions used in the wrong way because it’s not within the scope of the question and it’s a more complex subject. I leave a list of questions that may help, but I know that no one reads and keeps doing wrong.

  • Didn’t solve it, what else would you like me to post?

  • 2

    "It didn’t solve" doesn’t help much, you could talk more about it. programming is not worked or not, is to understand what is happening, is to detail the problem. Without this, I can not say what else should put. It is likely that the error has changed, but it is necessary to give information. Every programmer must understand what is necessary to understand the problem, otherwise he is not programming. See: [mcve].

  • I added more information.

0


I found out what it was, watching the debug, I noticed that the dao was null, so I used the injection on it instead of instantiating it, making it work.

@Inject
HabilidadeDAO dao;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.