You need to sign in to do that
Don't have an account?

While Adding values to array,I'm getting this error System.NullPointerException: Attempt to de-reference a null object
Hi
Visualforce Code :
While Adding values to array,I'm getting this error System.NullPointerException: Attempt to de-reference a null object at line 17.
In debugging I am getting the values whatever I entered
.Then why it is showing Nullpointer exception
Visualforce Code :
<apex:page controller="StringListEx" showheader="false" > <apex:form > <apex:pageblock > Name <apex:inputtext value="{!firVal}"/> code <apex:inputtext value="{!secVal}"/> Color <apex:inputtext value="{!thirdVal}"/> Class <apex:inputtext value="{!fourthVal}"/> <apex:commandButton value="Display" action="{!dislay}"/> </apex:pageblock> </apex:form> </apex:page>Apex/Controller Code :
public with sharing class StringListEx { public StringListEx (){ } public List<String> strLst; public String firVal { get; set; } public String secVal { get; set; } public String thirdVal { get; set; } public String fourthVal { get; set; } public PageReference dislay() { System.debug('First element value::::::::::::::'+firVal); System.debug('Second value::::::::::::::'+secVal); System.debug('Third value::::::::::::::::'+thirdVal); System.debug('Fourth value:::::::::::::::'+fourthVal); strLst.add(firVal); strLst.add(secVal); strLst.add(thirdVal); strLst.add(fourthVal); return null; } }
While Adding values to array,I'm getting this error System.NullPointerException: Attempt to de-reference a null object at line 17.
In debugging I am getting the values whatever I entered
.Then why it is showing Nullpointer exception
All Answers
Please try the following code.
1. You have to create the instance of the list variable.
2. before add any value to list, you must check the it is null or not.
public with sharing class StringListEx {
public StringListEx (){
}
public List<String> strLst;
public String firVal { get; set; }
public String secVal { get; set; }
public String thirdVal { get; set; }
public String fourthVal { get; set; }
public PageReference dislay() {
strLst = new List<String>();
System.debug('First element value::::::::::::::'+firVal);
System.debug('Second value::::::::::::::'+secVal);
System.debug('Third value::::::::::::::::'+thirdVal);
System.debug('Fourth value:::::::::::::::'+fourthVal);
if(String.isNotBlank(firVal))
strLst.add(firVal);
if(String.isNotBlank(secVal))
strLst.add(secVal);
if(String.isNotBlank(thirdVal))
strLst.add(thirdVal);
if(String.isNotBlank(fourthVal))
strLst.add(fourthVal);
return null;
}
}
Thanks & Regards,
Ranjeet Singh.
Thanq for reply .Ranjeet.
But my doubt is I checked in debug statements I got values .then why I should check in it is null or blank ?
Finally I Came to know one thing,
I need to Intialize list
Without writing if(firVal!=null) OR if(String.isNotBlank(secVal)) also it works .
Thanq very much for replying