function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ajith MDAjith MD 

Im getting error like this uplicateaccount: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.duplicateaccount: line 21, column 1: [].

My code is trigger duplicateaccount on Account (before insert, after insert) {
  
    List<Account> st = new List<Account>();
    st = [SELECT CreatedDate FROM Account ORDER BY CreatedDate DESC NULLS LAST LIMIT 1];
    for(Account a: Trigger.new){
        
    for(Account acc:st){
        System.debug('createddate' + acc.CreatedDate);
        Datetime firsttime = System.now();
        System.debug('first time' + firsttime);
        Datetime secondtime = Datetime.valueOf(acc.CreatedDate);
        System.debug('Secondtime' + secondtime);
        Decimal millisecondsBetween = firstTime.getTime() - secondTime.getTime();
        System.debug(millisecondsBetween);
        Decimal timeBetween = millisecondsBetween / 3600000; 
        decimal timediff = timeBetween.setscale(0);
        System.debug('diif'+timediff);
        
        if(timediff > 1) {    
            for(Account temp: st){
                Account objAccount = Trigger.newMap.get(temp.id);
                objAccount.addError('one hour');            
            }
            
        }
    }
    }

}

Can anyone help me how to resolve this.
Janet EpebinuJanet Epebinu
Hi Ajith MD,
 Check the changes I made to your code.

 
trigger duplicateAccount on Account (after insert) {

    List<Account> st = new List<Account>();
    st = [SELECT CreatedDate FROM Account Where Id IN :Trigger.newMap.keyset() ORDER BY CreatedDate DESC NULLS LAST LIMIT 1];
    Decimal timediff = 0.0;
    for(Account a: st){
      //for(Account ac: st){  
    
        System.debug('createddate' + a.CreatedDate);
        Datetime firsttime = System.now();
        System.debug('first time' + firsttime);
        Datetime secondtime = Datetime.valueOf(a.CreatedDate);
        System.debug('Secondtime' + secondtime);
        Decimal millisecondsBetween = firstTime.getTime() - secondTime.getTime();
        System.debug(millisecondsBetween);
        Decimal timeBetween = millisecondsBetween / 3600000; 
        timediff = timeBetween.setscale(0);
        System.debug('diif'+timediff);
       
        }
    
    if(timediff >= 0) { 
        
           for(Account temp: st){
               System.debug('temp'+ temp);
                /* Account objAccount = (Account)Trigger.newMap.get(temp.id);
                objAccount.addError('one hour'); */           
            }
}
}

I commented out the last two lines of code because you can easily uncomment it to achieve your use case.

I changed the condition of the timediff because the value I was getting  was less than 1 . 

Hope it helps you