+ Start a Discussion
Michael MMichael M 
I am parsing JSON that is coming back from  REST callout, and when running, it is throwing this error: attempt to de-reference null object. The issue seems to be with how I am parsing the JSON, but I am not sure where I am going wrong. Can someone help?

Here is the snippet of the JSON I am parsing:
"result": {
"first_name": "JOHN",
"last_name": "SMITH",
"id_type": "MI",
"subscriber_id": "1234567",
"gender": "M",
"birthdate": "19601119",
"address": {
"info": "123 Main St.",
"city": "New York",
"state": "NY",
"zip_code": "100000"
},
"county:": {
"value": "14"
},
"office": {
"value": "H78"
},
"recert_month": {
"value": "12",
"name": "December"
},
"dates": [
{
"name": "Service",
"qualifier": "472",
"date": "2020-09-29"
},
{
"name": "Plan Begin",
"qualifier": "346",
"date": "2020-09-01"
},
{
"name": "Issue",
"qualifier": "102",
"date": "2020-06-01"
}
],


Here is how I am parsing it (bold part is causing error):
  
        Map<String, Object> wholeResponse = (Map<String, Object>) JSON.deserializeUntyped(response2.getBody());
            Map<String, Object> result = (Map<String, Object>) wholeResponse.get('result');
                Map<String, Object> residentAddress = (Map<String, Object>) result.get('address');
                   Map<String, Object> county = (Map<String, Object>) result.get('county');
                  Map<String, Object> office = (Map<String, Object>) result.get('office');
                 Map<String, Object> recert_month = (Map<String, Object>) result.get('recert_month');
        
       Eligibility__c newEligRec = new Eligibility__c(); 
        newEligRec.Referral_Name__c = ref.id;
        newEligRec.First_Name__c = string.valueof(result.get('first_name'));
        newEligRec.Last_Name__c = string.valueof(result.get('last_name'));
        newEligRec.Name_Id_Type__c = string.valueof(result.get('id_type'));
        newEligRec.Client_ID__c = string.valueOf(result.get('subscriber_id'));
        newEligRec.Gender__c = string.valueOf(result.get('gender'));
        string birthdate;
              if (string.valueof(result.get('birthdate')) != null){
                  birthdate = string.valueof(result.get('birthdate')).remove('-');
                  string year = birthdate.substring(0,4);
                  string month = birthdate.substring(4,6);
                  string day = birthdate.substring(6,8);
                 birthdate = month + '/' + day + '/' + year;
                    }
        newEligRec.Date_of_Birth__c = birthdate;
        newEligRec.Address_Number_and_Street__c = string.valueOf(residentAddress.get('info')); 
        newEligRec.City__c =  string.valueOf(residentAddress.get('city'));    
        newEligRec.State__c =  string.valueOf(residentAddress.get('state'));    
        newEligRec.Zip_Code__c = string.valueOf(residentAddress.get('zip_code'));
        newEligRec.County__c = string.valueOf(county.get('value'));
        newEligRec.Office__c = string.valueOf(office.get('value'));
        newEligRec.Recertification_Month_value__c = string.valueOf(recert_month.get('value'));
        newEligRec.Recertification_Month__c = string.valueOf(recert_month.get('name'));
Best Answer chosen by Michael M
Maharajan CMaharajan C
HI Michael,

The problem is : we have extra colon in county on JSON with in the double quotes .  So it's causing the attempt to de-reference null.
See the extra colon inside county double quotes -->  "county:" : { "value": "14" }  .

So change the below line: Add the extra colon in county string like below. This change will resolve your issue.
Map<String, Object> county = (Map<String, Object>) wholeResponse.get('county:');

Other wise the external system hava to remove this colon from the JSON.

Thanks,
Maharajan.C
HanumanHanuman 
Hi all,
When custom button in detail page of  custom object is clicked i'm generating the PDF . I want to send the generated PDF as email. Can  we do this...?
Can anyone help me over here.

Thanks in advance.
Best Answer chosen by Hanuman
Amit Singh 1Amit Singh 1
Hello,

Use below code.
 
-- JavaScript --
{!requireScript("/soap/ajax/16.0/connection.js")}
{!requireScript("/soap/ajax/16.0/apex.js")}
var a = sforce.apex.execute("SendEmail","emailPdf",{localId:"{!Application__c.Id}"});

-- Apex Class Method --
public void SendEmail(Id localId){
 Application__c inv = [Select Id, name From Application__c Where Id=:localId];
 PageReference pdf = Page.PDFpage;// Replace PdfOfInvoice with your Page which render as PDF.
 pdf.getParameters().put('id', localId);
// Blob b = pdf.getContentAsPDF();
 Blob b;
 if (Test.IsRunningTest()){b=Blob.valueOf('UNIT.TEST');}else{b = pdf.getContentAsPDF();}
 // Create Attachment Object to attach with Email
 Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
 efa.setFileName(inv.Name+'.pdf');
 efa.setBody(b);
 // Define the email
 Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
 // Sets the paramaters of the email
 email.setSubject('PDF of Invoice - '+inv.Name);
 email.setToAddresses( new List<String>{inv.Email__c} );
 //email.setbccAddresses( new List<String>{'admin@gmail.com'} );
 email.sethtmlBody('Hi '+inv.Name+',<br/><br/> '
                        +'Please find the attached Invoice.'
                        +'<br/><br/>'+'Thanks,'+'<br/>'
                        +UserInfo.getName()+'<br/>'
                        +UserInfo.getOrganizationName());
 email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});

 try{
      Messaging.SendEmailResult [] result = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
 }catch(System.Exception e){
     
 }
Let me know if this helps :)

Thanks,
Amit Singh

 
George Laird 39George Laird 39 
Can someone help me with a report formula?  How can I get a net of the PAYMENT - REFUND for each payment type?   



User-added image
Best Answer chosen by George Laird 39
Maharajan CMaharajan C
Got it George...

update the formula custom sumary formula like below: 

Formula:  PREVGROUPVAL(Total:SUM, TYPE)  - Total:SUM

Classic  Report Screenshot:

User-added image


Lightning Report Screenshot:

User-added image

User-added image


And Final Ouput will be like below:

User-added image


Thanks,
Maharajan.C


 
Sophia GSophia G 
Hi,
I am having trouble with my Visualforce page and Apex Class. Everything seems to be fine apart from the error Unknown Property 'NFOSDisplayDivisions2Controller.Division_Space2__c'. I can't seem to figure out what is going on, could someone please help me out. Thank you.

Apex Class:
public with sharing class NFOSDisplayDivisions2Controller {
    
    public List<DivisionWrapper> listDivisionWrapper{get;set;}
    public List<Division_Space2__c> selectedDivisions{get;set;}

    public NFOSDisplayDivisions2Controller ()
    {
            listDivisionWrapper = new List<DivisionWrapper>();
            searchRecord();
    }
    
    public void searchRecord()
    {
        listDivisionWrapper.clear();
            for(Division_Space2__c a: [select Id, Name,Number_of_Competitors__c, Availability__c, RecordTypeID ,Active__c from Division_Space2__c limit 30]) 
            {
                listDivisionWrapper.add(new DivisionWrapper(a));
            }
    }

    public void processSelected() 
    {
        selectedDivisions = new List<Division_Space2__c>();
        selectedDivisions.clear();
        for(DivisionWrapper wrapDivisionObj : listDivisionWrapper) 
        {
            if(wrapDivisionObj.selected == true) 
            {
                selectedDivisions.add(wrapDivisionObj.acc);
                // Here you can add the counter or you check the selectedAccounts.size()
            }
        }
    }

    public void ActivateData() 
    {
        for(Division_Space2__c acc : selectedDivisions )
        {
            acc.Active__c= true;
        }
        update selectedDivisions ;
        searchRecord();
    }

    public void DeActivateData() 
    {
        for(Division_Space2__c acc : selectedDivisions )
        {
            acc.Active__c = false;
        }
        update selectedDivisions ;
        searchRecord();
    }
    


    // This is our wrapper/container class. 
    public class DivisionWrapper 
    {
        public Division_Space2__c acc {get;set;}
        public Boolean selected {get;set;}
        public DivisionWrapper(Division_Space2__c a) 
        {
            acc = a;
            selected = false;
        }
    }

}

Visualforce Page:
<apex:page controller= "NFOSDisplayDivisions2Controller">
    
<script type="text/javascript">
        function selectAllCheckboxes(obj,receivedInputID){
            var inputCheckBox = document.getElementsByTagName("input");
            for(var i=0; i<inputCheckBox.length; i++){
                if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
    </script>
    <apex:form >
        <apex:pageBlock id="PB1">
            <apex:pageBlockButtons >
                <apex:commandButton value="Add to Grid" action="{!processSelected}" rerender="table2,PB2"/>
            </apex:pageBlockButtons>

            <apex:pageblockSection title="Division Types" collapsible="false" columns="1">
                <apex:pageBlockTable value="{!listDivisionWrapper}" var="accWrap" id="table" title="Division Types">
                    <apex:column >
                        <apex:facet name="header">
                            <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                        </apex:facet>
                        <apex:inputCheckbox value="{!accWrap.selected}" id="inputId"/>
                    </apex:column>
                    <apex:column value="{!Division_Space2__c.acc.Name}" />
                    <apex:column value="{!Division_Space2__c.acc.Number_of_Competitors__c}" />
                    <apex:column value="{!Division_Space2__c.acc.Availability__c}" />
                    <apex:column value="{!Division_Space2__c.acc.Active__c}" />
                </apex:pageBlockTable>


            </apex:pageblockSection>
        </apex:pageBlock>
        
        <apex:pageBlock id="PB2" >
            <apex:pageBlockButtons >
                <apex:commandButton value="Activate" action="{!ActivateData}" rerender="PB1,PB2"/>
                <apex:commandButton value="DeActivate" action="{!DeActivateData}" rerender="PB1,PB2"/>
            </apex:pageBlockButtons>

                <apex:pageBlockTable value="{!selectedDivisions}" var="c" id="table2" title="Selected Divisions">
                    <apex:column value="{!c.Name}" headerValue="Division Type"/>
                    <apex:column value="{!c.Number_of_Competitors__c}" headerValue="Number of Competitors"/>
                    <apex:column value="{!c.Availability}" headerValue="Availability"/>
                    <apex:column value="{!c.Active__c}" headerValue="Active"/>
                </apex:pageBlockTable>
        </apex:pageBlock>

        
    </apex:form>
</apex:page>
Best Answer chosen by Sophia G
Maharajan CMaharajan C
Hi Sophia,

In the first pageblocktable you are wrongly refering the properties:

 <apex:column value="{!Division_Space2__c.acc.Name}" />  ==>  <apex:column value="{!accWrap.acc.Name}" />


Visualforce Page:
<apex:page controller= "NFOSDisplayDivisions2Controller">
    
<script type="text/javascript">
        function selectAllCheckboxes(obj,receivedInputID){
            var inputCheckBox = document.getElementsByTagName("input");
            for(var i=0; i<inputCheckBox.length; i++){
                if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
    </script>
    <apex:form >
        <apex:pageBlock id="PB1">
            <apex:pageBlockButtons >
                <apex:commandButton value="Add to Grid" action="{!processSelected}" rerender="table2,PB2"/>
            </apex:pageBlockButtons>

            <apex:pageblockSection title="Division Types" collapsible="false" columns="1">
                <apex:pageBlockTable value="{!listDivisionWrapper}" var="accWrap" id="table" title="Division Types">
                    <apex:column >
                        <apex:facet name="header">
                            <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                        </apex:facet>
                        <apex:inputCheckbox value="{!accWrap.selected}" id="inputId"/>
                    </apex:column>
                    <apex:column value="{!accWrap.acc.Name}" />
                    <apex:column value="{!accWrap.acc.Number_of_Competitors__c}" />
                    <apex:column value="{!accWrap.acc.Availability__c}" />
                    <apex:column value="{!accWrap.acc.Active__c}" />

                </apex:pageBlockTable>


            </apex:pageblockSection>
        </apex:pageBlock>
        
        <apex:pageBlock id="PB2" >
            <apex:pageBlockButtons >
                <apex:commandButton value="Activate" action="{!ActivateData}" rerender="PB1,PB2"/>
                <apex:commandButton value="DeActivate" action="{!DeActivateData}" rerender="PB1,PB2"/>
            </apex:pageBlockButtons>

                <apex:pageBlockTable value="{!selectedDivisions}" var="c" id="table2" title="Selected Divisions">
                    <apex:column value="{!c.Name}" headerValue="Division Type"/>
                    <apex:column value="{!c.Number_of_Competitors__c}" headerValue="Number of Competitors"/>
                    <apex:column value="{!c.Availability}" headerValue="Availability"/>
                    <apex:column value="{!c.Active__c}" headerValue="Active"/>
                </apex:pageBlockTable>
        </apex:pageBlock>

        
    </apex:form>
</apex:page>

Thanks,
Maharajan.C

 
Amine ElkhaAmine Elkha 
Hi all, 

I am on Create Object-Specific Quick Actions unit on Trailhead and somehow when I get to Test the Action in the Salesforce Mobile App, nothing happens on the app. I cannot see the Properties Custom Object even in the navigation menu. I have been following all the steps exactly as they appear on each task, one by one and I also passed the challenge. So, clearly I am doing the right thing, but it bugs me that I cannot see the results on the Mobile App.

I have tried everything and looked everywhere but it seems that my Salesforce App is not connected to Trailhead or something! I apologise in advance if I am not making any sense as I am new to Salesforce. 

I would really appreciate it if anyone have been through the same issue and found a solution or workaround. 

Many Thanks.
A
Best Answer chosen by Amine Elkha
SwethaSwetha (Salesforce Developers) 
HI ,
We have a separate Trailhead team who can help you with these issues. So, can you please use the below link to reach out to them so that one of the Engineers will get in touch with you.
Support: https://trailhead.salesforce.com/en/help?support=home

Please mark this answer as best if it helps so that others facing same issue will find it useful.Thanks
Saloni KhedkarSaloni Khedkar 
I have a custom object which has a list of products, country field and checkbox- inactive.

Use case: 
When I create an opportunity and add OpportunityLineItem, The line item should compare with the products field from the custom object.
Also, the Opportunity should look at Bill to country from the account attached and compare with the country field from the custom object.
And if the record matches and the "Inactive" checkbox from the custom object is true, then it should throw an error and not allow to save the opportunity.

For example,
Custom object:
Product: Pencil
Country: Mexico
Inavtive: True

Opportunity:
OpportunityLineItem: Pencil
Account - Bill to Country: Mexico
ERROR FLAG

Can this be achievable ? If so, can i receive some help on building the trigger ?

Thank you in advance.
Best Answer chosen by Saloni Khedkar
Maharajan CMaharajan C
Hi Saloni,

We can write trigger to handle this scenario:

Please refer the below code:

am considering Product__c  as Custom Object in below code
 
trigger OpportunityProductCheck on OpportunityLineItem (before insert) {
	set<Id> oppIds = new set<id>();
    set<Id> prodIds = new set<Id>();
    map<String,Boolean> prodcheckMap = new map<String,Boolean>();
    for(OpportunityLineItem oli : Trigger.New){
        oppIds.add(oli.OpportunityId);
        prodIds.add(oli.Product2Id);
    }
    Map<Id,Opportunity> oppMap = new Map<Id,Opportunity>([Select Id,Account.BillingCountry from Opportunity where ID IN: oppIds]);
    Map<Id,Product2> prodMap = new Map<Id,Product2>([Select Id,Name from Product2 where Id IN: prodIds]);
    for(Product__c prod : [Select Id,Inactive__c,Product__c,Country__c from Product__c]){
        String key = '';
        if(!String.isEmpty(prod.Product__c) && !String.isEmpty(prod.Country__c)){
            key = prod.Product__c + prod.Country__c;
            prodcheckMap.put(key, prod.Inactive__c);
        }
    }
    
    for(OpportunityLineItem oli : Trigger.New){
        string prodName = prodMap.containsKey(oli.Product2Id) ? prodMap.get(oli.Product2Id).Name : '';
        string acccountry = oppMap.containsKey(oli.OpportunityId) ? oppMap.get(oli.OpportunityId).Account.BillingCountry : '';
        //string olikey = prodMap.get(oli.Product2Id).Name + oppMap.get(oli.OpportunityId).Account.BillingCountry;
        string olikey = prodName + acccountry;
        if(prodcheckMap.containsKey(olikey)){
            boolean bool = prodcheckMap.get(olikey);
            if(bool){
                String errormsg = prodName + ' is Inactive for ' + acccountry;
                oli.addError(errormsg);
            }
        }
    }
}

Thanks,
Maharajan.C
Julie RajputJulie Rajput 
Hey, is there any WhatsApp group available for salesforce developers? I want to list down it on https://wagrouplink.com

thank you.
Best Answer chosen by Julie Rajput
AbhishekAbhishek (Salesforce Developers) 
Please be advised that this community is focused on Salesforce technical discussions where the forums and participants are geared toward programming troubleshooting and support. 

Please mark the answer best to close this thread.

Best regards
Salesforce Support
Ruma husainRuma husain 

 Any advice? The error is "Challenge Not yet complete... here's what's wrong: We could not find the correct tasks created from the "Bank Loan Opportunity" template according to the requirements. Make sure you created the action plan using the correct action plan template and created it logged in as the correct user. "
 
Best Answer chosen by Ruma husain
ANUTEJANUTEJ (Salesforce Developers) 
Hi Ruma,

Greetings!

There is a separate Trailhead team who can help you with these issues. So, can you please use the below link to reach out to them so that one of the agents will get in touch with you.

Support:https://trailhead.salesforce.com/help

Thank you!

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future.

Warm Regards,
Anutej
Athira VenugopalAthira Venugopal 
public class AccountProcessor {
 
    public AccountProcessor() {
      
    }
    public static void countContacts() {
       
        Account acc = [Select Id, Name from Account where name = 'chandra'];
Contact[] con = [SELECT Id,FirstName,LastName FROM Contact where AccountId =:acc.Id];
        acc.Number_of_Contacts__c = con.size();
        update acc;
        
        
    }
}
I am trying to update the 'Number of contacts' field in Account object.
Tried to call the countContacts() from anonymous window, But this exception occurs
AccountProcessor.countContacts();
Best Answer chosen by Athira Venugopal
Athira VenugopalAthira Venugopal
I tried it, but shows an error like this
"Expression must be a list type: Account"
So I tried like this:

public class AccountProcessor {
 
    public AccountProcessor() {
      
    }
    public static void countContacts() {
       
        Account acc = [Select Id, Name from Account where name = 'chandra'][0];
        Contact[] con = [SELECT Id,FirstName,LastName FROM Contact where AccountId =:acc.Id];
        acc.Number_of_Contacts__c = con.size();
        update acc;
        
        
    }
}

and it works, anyway thanks.
Brian KesslerBrian Kessler 
I'm currently on the last challenge for the Business Administration Specialist Superbadge.
I've uploaded both a photo for left of the header and a photo for the banner above the header.

Yet when I submit, I get this error:

Challenge Not yet complete... here's what's wrong: 
Couldn't find a photo assigned to the Chatter group.

What do I need to do to pass this challenge?

Thanks in advance,
-Brian.


 
Best Answer chosen by Brian Kessler
Brian KesslerBrian Kessler
Found the problem.
I accidentally named the Group "Residential Sales Product Collaboration." instead of "Residential Sales Product Collaboration".

A good test might have ignored the period or complained about it.
Instead it ignored that it couldn't find the group (since it wanted an exact match) and complained about something that actually worked.

:-/