algone
algone

Reputation: 93

Invoking a managed bean method returns a NPE

I have a simple question, why do i always get a NPE when I invoke a managed bean method that either returns a list. I am using primefaces wizard component in my view. For instance can sometone tells me the difference between these two:

Does not work:

public List<RequiredParam> getRequiredFields() {
   if(!this.sdeCommand.getActions().isEmpty() &&this.action!=null &&!this.action.equals("")){
       for(CommandAction act:this.sdeCommand.getCommandActions()){
           if(act.getActionName().equalsIgnoreCase(this.action)){
               this.requiredFields.addAll(act.getFields());
           }
       }
   }
    return this.requiredFields;
}

However this Works:

public List<RequiredParam> getRequiredFields() {

    return this.requiredFields;
}

The view:

                                <c:forEach items="${gdsiGeodataBean.requiredFields}" var="reqs">
                                    <h:outputLabel for="#{reqs.name}" value="#{reqs.name}:* " />  
                                </c:forEach>

Error message:

java.lang.NullPointerException
    com.tsystems.appbeans.GdsiGeodataBean.getRequiredFields(GdsiGeodataBean.java:103)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    java.lang.reflect.Method.invoke(Method.java:597)
    javax.el.BeanELResolver.getValue(BeanELResolver.java:62)
    com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    org.apache.el.parser.AstValue.getValue(AstValue.java:118)
...

my view:

Upvotes: 1

Views: 286

Answers (1)

maple_shaft
maple_shaft

Reputation: 10463

this.sdeCommand.getActions().isEmpty()

The above will throw an NPE if getActions() returns null. Check to make sure that getActions() != null first. This may or may not be your problem but it certainly is unsafe code and it should never pass a formal code review.

Upvotes: 1

Related Questions