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
gazzer82gazzer82 

Batch APEX, Attempt to de-reference a null object error?

Hi All,

 

I am trying to write my first APEX Batch script and failing miserable at it, this is what i have so far, but it keeps failing with the error "Attempt to de-reference a null object" which i am a little confused about as the only comparison i have to null is on the SOQL query, which i have tested and works fine in isolation.

 

Here is the code, woudl really appreciate some pointers.

 

I am exectuting manually using:

 

mileage_bulk b = new mileage_bulk();

database.executeBatch((b), 10);

 

And the class is as follows:

 

global class mileage_bulk implements Database.Batchable<sObject>,

  Database.AllowsCallouts

{

global Database.QueryLocator start(Database.BatchableContext BC)

{

String query = 'SELECT Id,Name,Amount,R2_Job_Ref__c,R2_Shipping_Post_Code__c FROM Opportunity WHERE R2_Shipping_Post_Code__c != null';

return Database.getQueryLocator(query);

}

 

global void execute(Database.BatchableContext BC, List<Opportunity> scope)

{

system.debug(scope);

for(Opportunity a : scope)

{

 

        String startPostcode = null;

        String endPostcode =   a.R2_Shipping_Post_Code__c;

        Pattern nonWordChar = Pattern.compile('[^\\w]');

endPostcode = nonWordChar.matcher(endPostcode).replaceAll('');

        String endPostcodeEncoded =   EncodingUtil.urlEncode(endPostcode, 'UTF-8');

        Double totalDistanceMeter = null;

        Integer totalDistanceMile = null;

       String responseBody = null;

       Boolean firstRecord = false;

        

        String ukPrefix = 'UKH';    

        if ((a.R2_Job_Ref__c).toLowerCase().contains(ukPrefix.toLowerCase())){

        startPostcode = EncodingUtil.urlEncode('HP27DU', 'UTF-8');

        } else {

        startPostcode = EncodingUtil.urlEncode('B604AD', 'UTF-8');

        }

        // build callout

        Http h = new Http();

        HttpRequest req = new HttpRequest();

        req.setEndpoint('http://maps.googleapis.com/maps/api/directions/json?origin='+startPostcode+'&destination='+endPostcodeEncoded+'&units=imperial&sensor=false');

        req.setMethod('GET');

        req.setTimeout(60000);

 

try{  

            // callout

            HttpResponse res = h.send(req);

            

            // parse coordinates from response

            JSONParser parser = JSON.createParser(res.getBody());

            

            responseBody = res.getBody();

            //system.debug(responseBody);

            

            while (parser.nextToken() != null) {

                if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && 

                    (parser.getText() == 'distance')){

                       parser.nextToken(); // object start

                       while (parser.nextToken() != JSONToken.END_OBJECT){

                           String txt = parser.getText();

                           parser.nextToken();

                           //system.debug(parser.nextToken());

                           //system.debug(txt);

                           if (firstRecord == false){

                           //if (txt == 'text'){

                               //totalDistanceMile = parser.getText();

                               //system.debug(parser.getText());

                           //}

                           if (txt == 'value'){

                               totalDistanceMeter = parser.getDoubleValue();

                               double inches = totalDistanceMeter*39.3701;

                               totalDistanceMile = (integer)inches/63360;

                               system.debug(parser.getText());

                               firstRecord = true;

                           }

                           }

                       }

                    

                }

            }

            

            // update coordinates if we get back 

            if (totalDistanceMile != null){

                //a.DistanceM__c = totalDistanceMile;

                //a.Shipping_Postcode_2__c = a.R2_Shipping_Post_Code__c;

                //a.Location__Longitude__s = lon;

                //update a;        

            }    

           

        } catch (Exception e) {

        }

 

//system.debug(accountId);

        system.debug(a);

        system.debug(endPostcodeEncoded);

        system.debug(totalDistanceMeter);

        system.debug(totalDistanceMile);

 

}

}

 

 

global void finish(Database.BatchableContext BC)

{

}

}

gazzer82gazzer82

Actually worked it our for myself, a mear minutes after posting, isn't that always the way:

 

I was setting a sub-string without checkig to see if it was null:

 

String endPostcode =   a.R2_Shipping_Post_Code__c;

 

Stuck it in a null check and now all is fine :)

 

 

Cheers

 

Gareth