Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
public with sharing class NameUpdates 
{
    public list<account> display()
    {
        list<account>acc = [Select name from account limit 50];
        list<account>accupd;
        for(account acc1:acc)
        {
            if(acc1.name == 'Rahul')
            {
                acc1.name = 'Ronak';
                accupd.add(acc1);
                update accupd;

            }    
        }
            return accupd;
    }
}   

Its shows an errorenter image description here

Line: 12, Column: 1 System.NullPointerException: Attempt to de-reference a null object

share|improve this question
up vote 2 down vote accepted

Initialize first list<account>accupd = new list<account>();

If you don't initialize means list is null.

Also perform DML outside of for loop. if there is more than 150 records in list then you will receive 151 DML exception..

Because there is limit we can use 150 DML per transaction..

public with sharing class NameUpdates 
{
    public list<account> display()
    {
        list<account>acc = [Select name from account limit 50];
        list<account>accupd = new list<account>();
        for(account acc1:acc)
        {
            if(acc1.name == 'Rahul')
            {
                acc1.name = 'Ronak';
                accupd.add(acc1);
            }    
        }
        update accupd;
       return accupd;
    }
}
share|improve this answer
1  
Thanks Ratan.You are always helpful. – Bonny Jan 27 at 7:13
    
@Bonny always welcome.. – Ratan Jan 27 at 7:15

There are two things wrong in your code:

1- You need to initialize your list "accupd" before adding elements

into it.

2- You need to move the DML outside of for loop.

public with sharing class NameUpdates 
{
    public list<account> display()
    {
        list<account>acc = [Select name from account limit 50];
        list<account>accupd = new list<account>();
        for(account acc1:acc)
        {
            if(acc1.name == 'Rahul')
            {
                acc1.name = 'Ronak';
                accupd.add(acc1);


            }    
        }
        update accupd;
        return accupd;
    }
}
share|improve this answer
    
Thanks Nitin.Its worked – Bonny Jan 27 at 7:14

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.