Activity Forums Salesforce® Discussions How to solve “System.NullPointerException: Attempt to de-reference a null object” in Salesforce apex class?

  • Kumar

    Member
    February 9, 2017 at 8:14 am

    Hi Sushant,

    The error “System.NullPointerException: Attempt to de-reference a null object” normally occurs when you try to reference an object which has not been initialized or has null values.

    To avoid this you need to make sure that all the sObjects in your class are initialized, preferably in the constructor.

    Hope this helps.

  • Sachin

    Member
    September 8, 2017 at 9:16 am

    Hi Sushant

    “System.NullPointerException: Attempt to de-reference a null object”
    This is a very common error message which occurs when your object/list is not initialised (allocated memory). So when say not initialised means following:

    In order to use the non primitive data type in the code we have initialised the memory to those data types. For example:

    I want to use the Account object in my apex class, so I have allocate a memory to that object. So to do that I have to write:

    Account accountObj = new Account(); // allocating memory to the account.

    Similarly in case of list:

    list<Account> accountList  = new list<Account>(); // allocating memory to list of accounts.

    So in your code make sure you have allocated the memory to your non primitive data types, else you will ran into same error.

    Hope this helps, if not please attach your code.

    Thanks.

     

  • Guha

    Member
    September 23, 2017 at 1:23 am

    Try to initialize the list or object.

    For example:

    Public List<Account> acc {get;set;}

    acc = new List<Account>(); 

    Likewise whenever you use this list variable "acc". Try to check size before you do an update or iteration.

    Example:

    if(!accList.isEmpty()) {

    //Your code logic for accList.

    }

    Ref: http://npntraining.com/blog/2017/best-practices-to-avoid-nullpointerexception/

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos