+ Start a Discussion
Semira@gmail.comSemira@gmail.com 

System.NullPointerException: Attempt to de-reference a null object

Hi guys, 

I'm trying to query a field from an object to see what was the last number and increament the number by 1. Then assign that to a new record when it's created. But I'm getting null pointer on the query. Please someone point me why.

public PageReference save(){

List<Expense_Line_Item__c> insertExpenseList = new List<Expense_Line_Item__c>();
       
        insertExpenseList.add(ELI2);

Expense_Line_Item__c exp = new Expense_Line_Item__c();
        exp = [select expense__c, id, Number_of_item__c from Expense_Line_Item__c where expense__c =:ELI2.expense__c order by Number_of_item__c ASC limit 1];
        insertExpenseList[0].Number_of_item__c = exp.Number_of_item__c+1;
.......
}
I have this in my construction:

this.ELI2 = (Expense_Line_Item__c)controller.getRecord();

I have tried assigning just a single number instead of the query. It runs fine but as soon as I assign exp.Number_of_item__c+1, it gives error. 
Best Answer chosen by Semira@gmail.com
MaxPowerForceMaxPowerForce
If Number_of_Item__c is null, you need to initialize it before you can add anything to it:

if(exp.Number_of_item__c == null) exp.Number_of_item__c = 0;
insertExpenseList[0].Number_of_item__c = exp.Number_of_item__c+1;

All Answers

MaxPowerForceMaxPowerForce
If Number_of_Item__c is null, you need to initialize it before you can add anything to it:

if(exp.Number_of_item__c == null) exp.Number_of_item__c = 0;
insertExpenseList[0].Number_of_item__c = exp.Number_of_item__c+1;
This was selected as the best answer
praveen murugesanpraveen murugesan
Hi Semira,

The query may return a null value so it showing the null point error. So you need to check the query first before assigning any value from the query.

Eg.

if(exp != null) 
{
     insertExpenseList[0].Number_of_item__c = exp.Number_of_item__c+1;
}

Thanks
Semira@gmail.comSemira@gmail.com
Thank you both. it was the number_of_item that was returning null.