+ Start a Discussion
SLockardSLockard 

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

Hi everyone,

 

I am getting a NullPointerException and I have no idea why. Here is a simplified version of the code:

global class batch_class  implements Database.Batchable < Sobject >
{

	global Id idOne; 
	global Id idTwo;
	global id idThree;
	global string query;
	
    global batch_class() {
    query='SELECT case.CreatedDate, case.Score__c, case.OwnerId, case.A_name__c, case.RecordTypeId, case.Origin FROM Case WHERE case.Origin = \'Email\' LIMIT 200';
    }
    
    global database.Querylocator start(Database.Batchablecontext ch) {
        return Database.getQueryLocator(query);
    }

    global void execute(Database.Batchablecontext ch, list<Case> list_Case) 
    {
		list<RecordType> list_rd=[select RecordType.Name, Id from RecordType where name=:'Name One' or name=:'Name Two'];
		for(RecordType loopRd:list_rd)
		{
			if(loopRd.Name=='Name One')
			{
				idOne=loopRd.Id;
			}else if(loopRd.Name=='Name Two')
			{
				idTwo=loopRd.ID;
			}
		}
		for(case loop_case:list_Case)
		{
			if(loop_case.RecordTypeId==idOne)
			{
				// do stuff .. 
			}
			else if(loop_case.RecordTypeId==idTwo)
			{
				if((loop_case.A_name__c=='Blah')||(loop_case.A_name__c=='One & Two')||(loop_case.A_name__c=='Another')||(loop_case.A_name__c=='Yes No'))
				{
					system.debug('>>Inside A case<>>> Agency name'+loop_case.A_name__c);
					loop_case.Score__c=loop_case.Score__c+2;
				}	 
			}
		}
	}  
    
    global void finish(Database.BatchableContext ch) {
        System.debug('<>>>>>>>>>>>>>>End >>>>>>>>>>>>>');
    }

}

 and the test case:

@isTest
private class batch_clas_TESTT {
    static testMethod void tClass() {

    User U = [SELECT Id FROM User WHERE Name = 'user U'];
     RecordType rType2 =[select Name, Id from RecordType where name='nameOne' LIMIT 1];
    RecordType rType1 =[select Name, Id from RecordType where name='nameTwo' LIMIT 1];
    List<Case> testCases = new List<Case>();
    
    Case caseR = new Case(Origin = 'Email', OwnerId=U.Id, Case_Type__c = 'blah', A_name__c = 'Blah', recordType = rType1, recordTypeId = rType1.Id);
    testCases.add(caseR);
    
    Case caseN = new Case(Origin = 'Email', OwnerId=U.Id, Case_Type__c = 'blah blah', A_name__c = 'Blah', recordType = rType2, recordTypeId = rType2.Id);
    testCases.add(caseN);
    
    insert testCases;
    
    Test.StartTest();
    
    batch_class bcs = new batch_class();
    Database.executeBatch(bcs, 200);
    
    Test.StopTest();    
    }
}

 I keep getting the null pointer exception for line 38, where it checks for case.A_name__c, however, I get to line 42 before it stops. I can see the debug statement at line 40, which debugs the correct value .. Any ideas? Thanks

Best Answer chosen by Admin (Salesforce Developers) 
SLockardSLockard

Nevermind, the field accessibility for the field was hidden. So I changed it to editable and was fine.