-1

I am having problem with getting data from the database (JavaDB). Exactly, I think the error is in the UserBean class in the method GetAllUsersFromTable. It is maybe bc I get entities incorrectly from the database. I have tried to write method GetAllUsersFromTable in few different ways but it doesn't work well.

My project works well until I don't try to get the data from the database. index page is displayed correctly, usersForm also display correctly and when I click submit button it display error. On the page were the error is displayed I should see table with all users.

I use the Glassfish 4.0 and JavaDB is build in. I don't use any IDE's like Eclipse or Netbeans. My project is managed by Maven.I use also JSF CDI ManagedBeans and JPA.

Please ask me any question. I would really love to solve this issue.

I get this error:


javax.faces.el.EvaluationException: java.lang.NullPointerException
    at   
javax.faces.component.MethodBindingMethodExpressionAdapter.invoke
  (MethodBindingMethodExpressionAdapter.java:101)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at   
    org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at  

 org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at 
org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at   
org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.
    run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.
    doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.NullPointerException
    at com.test.UserBean.getAllUsersFromTable(UserBean.java:119)
    at com.test.UserBean$Proxy$_$$_WeldClientProxy.getAllUsersFromTable(Unknown Source)
    at com.test.AllUsersBean.add(AllUsersBean.java:43)
    at com.test.AllUsersBean$Proxy$_$$_WeldClientProxy.add(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at javax.el.ELUtil.invokeMethod(ELUtil.java:326)
    at javax.el.BeanELResolver.invoke(BeanELResolver.java:536)
    at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:269)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at 
 javax.faces.component.MethodBindingMethodExpressionAdapter.invoke
(MethodBindingMethodExpressionAdapter.java:87)
    ... 35 more

Line 119 in the UserBean.java file is

user.setId(v.getId());


package com.test;

/*Importing required java libraries */
import java.io.Serializable;
import javax.inject.Named;
import javax.inject.Inject;  
import javax.enterprise.context.ApplicationScoped;
import java.util.ArrayList;
import java.util.List;

@Named("appBean")
@ApplicationScoped
public class AllUserssBean implements Serializable {

   private List<UserBean> users;
   private int id;

   @Inject
   private UserBean subBean;

   public AllUsersBean(){
      users = new ArrayList<UserBean>();
      id = 0;
   }

   public String add() throws Exception {
        subBean.addUserToTable();
        ++id;
        users.add(subBean.getAllUsersFromTable(id));
    subBean.reset();
    return "submit";
   }

   /*Get total number of users */
   public int getTotal(){ return users.size(); }

   public List<UserBean> getUsers() { return users; }
   public void setUsers(List<UserBean> users) { this.users = users; }   
}


package com.test;

/*Importing required java libraries */
import java.io.Serializable;
import javax.inject.Named; 
import javax.enterprise.context.SessionScoped;
import java.sql.*;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.transaction.UserTransaction;
import javax.transaction.RollbackException; 
import javax.persistence.*;
import java.util.List;
import java.util.*;

@Named("subBean")
@SessionScoped
public class UserBean implements Serializable{

   @PersistenceUnit(unitName="testMe")
   private EntityManagerFactory emf;

   @Resource
   private UserTransaction transaction;

   private int id; 
   private String fname;
   private String lname; 

   public UserBean() {
     this.fname = "";
     this.lname = "";
   }

   public int getId() { return id; }
   public void setId(int id) { this.id = id; }
   public String getFname() { return fname; }
   public void setFname(String fname) { this.fname = fname; }
   public String getLname() { return lname; }
   public void setLname(String lname) { this.lname = lname; }
   public UserTransaction getTransaction() { return transaction; }
   public void setTransaction(UserTransaction transaction) { this.transaction = transaction; }

   public void addUserToTable() throws Exception
        {

        EntityManager manager = emf.createEntityManager();
         boolean commit;
    try{
       transaction.begin();
           manager.joinTransaction();   
       commit = false;
        try {
        User v = null;
        v.setFname(fname);  
        v.setLname(lname);
        manager.persist(v);
        transaction.commit();
        commit = true;
         }finally {
                if(commit==false){
              transaction.rollback();
                }
         }

    } catch(Exception e) { 
             e.printStackTrace();
        }finally {     
         manager.close();
    }
   }


   public UserBean getAllUsersFromTable(int id) {
        EntityManager manager = emf.createEntityManager();
        User v = null;
        UserBean user = new UserBean();
    try {
        v = manager.find(User.class, id);
            user.setId(v.getId());
        user.setFname(v.getFname());
            user.setLname(v.getLname());
        }finally {
            manager.close();
        }   
    return user; 
   } 

  /*
   public List getAllUsersFromTable() throws javax.transaction.SystemException, 
   javax.transaction.NotSupportedException {
        EntityManager manager = emf.createEntityManager();
        User v = null;
        List<User> results;
    try {
            TypedQuery<User> query = 
                 manager.createQuery("SELECT * FROM User", User.class);
        results = query.getResultList();
        }finally {
            manager.close();
        }   
    return results; 
   } */

   /*reset method is used to set all the parameters to null and
     to 0. This method is called after user was added to the
     list of users */
   public void reset(){
    setFname("");
        setLname("");
   }
}


package com.test;

/*Importing required java libraries */
import java.io.Serializable;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.EntityManager;
import javax.persistence.Entity;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;


@Entity
public class User implements Serializable{

   @Id 
   @GeneratedValue 
   private int id; 
   private String fname;
   private String lname;

   public User() {}

   public int getId() { return id; }
   public void setId(int id) { this.id = id; }
   public String getFname() { return fname; }
   public void setFname(String fname) { this.fname = fname; }
   public String getLname() { return lname; }
   public void setLname(String lname) { this.lname = lname;} 
}

index.xhtml

<!DOCTYPE html  
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" lang="en"
  xmlns="http://www.w3.org/1999/xhtml" 
  xmlns:f="http://java.sun.com/jsf/core"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:ui="http://java.sun.com/jsf/facelets">

<h:head><title></title></h:head>
<h:body>
   <div style="text-align:center">
       <h1>Hello</h1>
       <p><h:link value="User Form" outcome="userForm"/></p>
       <p><h:link value="All users List" outcome="allUsersList"/></p>
   </div>
</h:body>
</html>

userForm.xhtml

<!DOCTYPE html  
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" lang="en"
  xmlns="http://www.w3.org/1999/xhtml" 
  xmlns:f="http://java.sun.com/jsf/core"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:ui="http://java.sun.com/jsf/facelets">

<h:head>
    <h:outputStylesheet library="css" name="template.css"/>
    <title>User Form page</title>
</h:head>
<h:body>
    <h:form id="submissionForm">
    <table border="0">

        <tr>
        <td><h:outputLabel for="fname" value="First name:"></h:outputLabel></td>
    <td><h:inputText id="firstName" value="#{subBean.fname}" maxlength="30" 
           requiredMessage="Please enter first name!" validatorMessage="First 
               name can include only letters. You can't live it empty!" > 
            <f:validateRegex pattern="[a-zA-Z]{1,30}"></f:validateRegex>
            </h:inputText></td>
        <td><h:message for="firstName" style="color:red;"></h:message></td>
        </tr>

        <tr>
        <td><h:outputLabel for="lname" value="Last name:"></h:outputLabel></td>
    <td><h:inputText id="lastName" value="#{subBean.lname}" maxlength="30" 
           requiredMessage="Please enter last name!" validatorMessage="Last 
               name can include only letters. You can't live it empty!" > 
            <f:validateRegex pattern="[a-zA-Z]{1,60}"></f:validateRegex>
            </h:inputText></td>
        <td><h:message for="lastName" style="color:red;"></h:message></td>
        </tr>

    <tr>
    <td colspan="3">
<h:commandButton id="submit" value="Submit" action="#{appBean.add()}" 
       style="float:right;margin-right:10px;"/>
    </td>
        </tr>

    </table>
        </h:form>  
</h:body>
</html>

allUsersForm.xhtml

<!DOCTYPE html  
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" lang="en"
  xmlns="http://www.w3.org/1999/xhtml" 
  xmlns:f="http://java.sun.com/jsf/core"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:ui="http://java.sun.com/jsf/facelets">

<h:head>
<title>List of All Users page</title>
</h:head>
<h:body>
 <h:form id="AllUsersListForm">  

  <h2><h:outputText value="The next election date: #{msgs.date}"/></h2><p></p>

  <h:dataTable value="#{appBean.users}" var="v">
   <h:column>
     <f:facet name="header"><h:outputText value="Id"></h:outputText></f:facet>
     <h:outputText value="#{v.id}"></h:outputText>      
   </h:column>

   <h:column>
     <f:facet name="header"><h:outputText value="First Name"></h:outputText></f:facet>
     <h:outputText value="#{v.fname}"></h:outputText>      
   </h:column>

   <h:column>
     <f:facet name="header"><h:outputText value="Last Name"></h:outputText></f:facet>
     <h:outputText value="#{v.lname}"></h:outputText>      
   </h:column>

   <f:facet name="footer"><h:outputText 
    value="The total number of users: #{appBean.getTotal()}"></h:outputText>      
   </f:facet>
  </h:dataTable>

  <p></p>
  <p><h:link value="Home page" outcome="index"/></p>

 </h:form>   
</h:body>
</html>

persistence.xml (It is placed under main/resources/META-iNF/perssitence.xml)

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" 
       xmlns="http://java.sun.com/xml/ns/persistence"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
         http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <persistence-unit name="test1" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>jdbc/username</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
      <property name="javax.persistence.schema-generation.database.action"
    value="drop-and-create"/>
      <property name="javax.persistence.schema-generation.create-source"
    value="metadata"/>
      <property name="javax.persistence.schema-generation.drop-source"
    value="metadata"/> 
     <property name="javax.persistence.jdbc.user" value="Us"/>
     <property name="javax.persistence.jdbc.password" value="Us"/>
    </properties>
  </persistence-unit>
</persistence>

When I go to (localhost:4848/common/index.jsf) I create JDBC Connection Pool and everything is correct. When I Ping I get success response I also create JDBC Connection Resource and everything is set up correctly

This is what we could use us an example to add data do database


public class AddingDatabase 
{ 
  @PersistenceUnit(unitName="test_db”) private EntityManagerFactory emf; 
  @Resource private UserTransaction utx; 

  void doDML(MyEntity e) throws SystemException, NotSupportedException, 
  javax.transaction.RollbackException,HeuristicMixedException,HeuristicRollbackException 
  { 
    EntityManager em = emf.createEntityManager(); 
    utx.begin(); 
    em.joinTransaction(); 

    try { 
        boolean committed = false; 
        try { 
            em.persist(e); 
            utx.commit(); 
            committed = true; 
        } finally { 
            if (!committed) utx.rollback(); 
        } 
    } 
    finally { 
       em.close(); 
    } 
  } 
} 

Tiny
  • 27,221
  • 105
  • 339
  • 599
user1282256
  • 183
  • 1
  • 6
  • 16

1 Answers1

1

This might not be the answer, but I need full formatting.

What are you doing in the following code?

    User v = null;
    v.setFname(fname);  
    v.setLname(lname);
    manager.persist(v);

How can it possibly not produce NPE?

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
  • Create reference to the User object and set first name and last name values. By using persist method I set up these data in the database. What is NPE? – user1282256 Jun 28 '14 at 02:08
  • 1
    You did **not** create a reference to any object. You kept it `null`, which simply means that the reference is not pointing to any place on the heap. In Java you cannot call any methods on `null`. This is **exactly** what causes [`NPE`](http://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html). – PM 77-1 Jun 28 '14 at 02:15
  • 1
    Please do not post any code in comments - edit your question instead. – PM 77-1 Jun 28 '14 at 02:16
  • So I assume you recommend write User v = new User(); Also, I posted example above. – user1282256 Jun 28 '14 at 02:22
  • Thank you so much that you checked my project. It is a lot to look at and figure out the error. The answer was exactly one you said. From the logic of my program I assume that the table was created. Unfortunately, I can't check it if I go to the Glassfish under the link I provided above. I just simply don't know where to look at. I clicked around but I didn't see any table. I mix here JSF with JPA. I have many things to do with this project yet. If I will get any other error should I continue in this thread or start a new one? – user1282256 Jun 28 '14 at 02:33
  • 1
    Yes, `User v = new User()` will indeed create a new object and you will at the very least avoid NPE. – PM 77-1 Jun 28 '14 at 02:34
  • 1
    It depends. If you have a different problem, then create a new question. If it's relevant you may then link your new question to the old one. – PM 77-1 Jun 28 '14 at 02:36