2
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

2

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;
    }
}
  • @Bonny always welcome.. – Ratan Paul Jan 27 '16 at 7:15
1

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;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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