I have an invocation target exception issue. I am having one object(window) which i am calling on a click of a button, now using that common button on two different User Interfaces. The problem is that when i click on it on one UI it shows me the data but when i click it on other UI it returns invocation target exception.   Code is:  @Override public void buttonClick(ClickEvent event) {      // This if block will be called when user clicks on list of      // document button      if(event.getButton() == mlistButton) {         try {             listButtonButtonClicked();         } catch (RequestDetailTableException | InvocationTargetException e) {             e.printStackTrace();         }     }      // this if block will be called when user clicks on Tracking button     if(event.getButton() == mtrackingButton) {         trackingButtonClicked();     }  }  /**  * This function will be called when user clicks on list of  * document button.  * @throws Exception   */ protected void listButtonButtonClicked() throws RequestDetailTableException {      DocumentListLayout ldocumentList = null;     try {         ldocumentList = new DocumentListLayout(mrequestInfoBean,mdetailRequestLayout.getGeoAISUI());     } catch (DocumentListLayoutException e) {         throw new RequestDetailTableException(e);     }     mdetailRequestLayout.getGeoAISUI().addWindow(ldocumentList); }    Stack Trace:  java.lang.NullPointerException  at org.ids.geoais.common.RequestDetailTable.listButtonButtonClicked(RequestDetailTable.java:306)  at org.ids.geoais.common.RequestDetailTable.buttonClick(RequestDetailTable.java:275)  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)  at java.lang.reflect.Method.invoke(Method.java:606)  at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:508)  at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:198)  at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:161)  at com.vaadin.server.AbstractClientConnector.fireEvent(AbstractClientConnector.java:995)  at com.vaadin.ui.Button.fireClick(Button.java:393)  at com.vaadin.ui.Button$1.click(Button.java:61)  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)  at java.lang.reflect.Method.invoke(Method.java:606)  at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:158)  at com.vaadin.server.ServerRpcManager.applyInvocation(ServerRpcManager.java:118)  at com.vaadin.server.communication.ServerRpcHandler.handleInvocations(ServerRpcHandler.java:313)  at com.vaadin.server.communication.ServerRpcHandler.handleRpc(ServerRpcHandler.java:202)  at com.vaadin.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:95)  at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:41)  at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1408)  at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:350)  at org.ids.geoais.Servlet.service(Servlet.java:160)  at javax.servlet.http.HttpSer   The compiler moves to this:      /**      * Constructs a InvocationTargetException with a target exception.      *      * @param target the target exception      */     public InvocationTargetException(Throwable target) {         super((Throwable)null);  // Disallow initCause         this.target = target;     }
129
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?  What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
105199
I am trying to edit an existing page with this code. When I am setting a publishComment it is throwing this exception.  item["Title"] = pageTitle; item["PublishingPageContent"] = pageContent; item.Update(); SharePointTools.ClientContext.ExecuteQuery(); item.File.Publish(publishComment); SharePointTools.ClientContext.ExecuteQuery();   What am I doing wrong? I need your help guys.
2217
The trigger:    What I have been trying for the test class:   I am a total noob when it comes to writing these unit tests. I would greatly appreciate any guidance to help me get this figured out.
90280
I am using LWCs to display lightning cards in a list.  The list shows information about Programs.  Each Program card has a button, and this button needs to take the user to the 'new object' screen of the Application object.  Here is my code:   applyToProgram(event) {     // The recordTypeId is coming from the .html     // I have verified that the value is correct.     var rtId = event.target.id;      // How do I use rtId below?     this[NavigationMixin.Navigate]({         type: 'standard__objectPage',         attributes: {             objectApiName: 'Application__c',             actionName: 'new',             nooverride: '1',             recordTypeId: rtId  // This does not work         }     }); }   This is not working.  The user is presented with the 'new object' screen for the object's default record type and NOT the one specified in rtId.  I tried putting 'nooverride' and 'recordTypeId' in the state:{} argument, and I also renamed 'recordTypeId' to just 'recordType'.  None of these worked.  Can anyone help me with the correct syntax?  Is this even possible in LWCs?  Thanks, Jeff
86786
I have a problem with my trigger. In Sandbox, everything works fine. When I deploy it to production, I receive multiple exceptions - which is really strange, because I got angry and put the whole code in &quot;try&quot; block. When I put everything in &quot;try&quot; block, it shouldn't be possible not to catch an exception! This is how my code looks: trigger UpdateLeadField on Lead (before insert, before update) {      //debugging in progress     try{         if(Trigger.New[0].SomeField__c==NULL)         {             for(Lead obj: trigger.new)                 obj.SomeField__c = obj.OwnerId;             return;         }              if (Trigger.New[0].OwnerId != Trigger.Old[0].OwnerId)          {             for(Lead obj: trigger.new)             {                 if(Trigger.New[0].SomeField__c==NULL || [SELECT Name FROM UserRole Where Id = :[SELECT Id, UserRoleId FROM User WHERE Id = :obj.OwnerId][0].UserRoleId].Name == 'Some role')                 obj.SomeField__c = obj.OwnerId;             }         }     }     catch (Exception e)     {         System.debug(e);     } }  The main problem seems to be with Web-to-Lead - When deployed, it stops working. The exception:  Apex script unhandled trigger exception by user/organization: 005C00000XXXXXX/00XXXXX0000LXXQ UpdateLeadField: data changed by trigger for field Some field: id value of incorrect type: 00GC00000XXXXXqMAC  &quot;Some field&quot; is a lookup field.
105631
Please consider the below scenario:   I have an Application__c object. I have a trigger on that (for simplicity, coded directly in trigger) which does one thing if the record name is Error then throws exception.     trigger ApplicationTrigger on Application__c (before insert, after update){          if(trigger.new[0].Name == 'Error'){             Application__c application;             System.debug(application.Name);         } }    Now I am running below code:     Now notice the catch statement is not executing, means system was not able to catch the exception. It came as the Fatal Error.   This is kind of a big issue where if there is null pointer or any other exception in trigger and exception handling code will not be able to do anything. Not even logging since it never reaches to catch block.   Let me know if you guys ever faced such situation and if yes what you did to make sure that it is properly caught.
44160
I have a Batch class that sends an Email from its finish method and want to test that. a But....I cannot test it. The the above test fails as there was no email invocation at all. BUT: I see it in the Limits view of my Dev Console that indeed one email invocation happens. Why?!  The batch class:  public MyBatch implements Database.Batchable&lt;SObject&gt; {      ...      public void finish(Database.BatchableContext context) {         sendEmail();     } }   The test method:  @isTest private static void sendsEmailOnFinish() {      Test.startTest();        MyBatch b = new MyBatch();     Database.executeBatch(b);     Test.stopTest();       // Verify     System.assertEquals(1, Limits.getEmailInvocations()); }   I thought this might be connected to using Test.startTest() and stopTest() but even moving the assertEquals before the Test.stopTest() doesn't make my test run.
44999
I am trying to write a test class for the Apex Class with try - catch block and this is my first time coding test classes. The Apex Class is like below which has trycatch   public class updateCaseRecord {          @AuraEnabled     public static void updateCheck(String caseId){         String msg = '';         try         {         List&lt;Case&gt; records = [select id,Status from Case WHERE Id = :caseId];         for (Case record : records)         {             record.Status = 'Closed';         }         update records;          }         catch(DmlException e)              {                for (Integer i = 0; i &lt; e.getNumDml(); i++) {                     msg =+ e.getDmlMessage(i) +  '\n' ;                     System.debug('getDmlFieldNames=' + e.getDmlFieldNames(i));                    System.debug('getDmlMessage=' + e.getDmlMessage(i));                   }                 throw new AuraHandledException(msg);             }             catch(Exception e)             {             throw new AuraHandledException(e.getMessage());             }             finally { }           }}   And I wrote my test class like   @IsTest public class updateCaseRecordTest { @IsTest static void testIsUpdateCheck() {      ID parentRecType = '012U0000000PqA9IAK';     ID csRecType     = '012U0000000QGv4IAG';       Account pa = new Account(Name='Test Parent Account', recordTypeId=parentRecType);     insert pa;      Account testAccount = new Account(Name='test', Industry='Biotech',Territory__c='EUR',BillingCity='Test',BillingCountry='Germany',ParentId=pa.id);     insert testAccount;       Contact c = new Contact(LastName='Test',LeadSource='Customer Service',AccountId=testAccount.Id);     insert c;      Case newCase1 = new Case();     newCase1.Subject = 'testStatusClosed';     newCase1.Status = 'New';     newCase1.Category__c = 'Inquiry';     newCase1.Sub_Category__c = 'Other';     newCase1.AccountId = testAccount.Id;     newCase1.ContactId = c.id;     newCase1.recordTypeId=csRecType;     insert newCase1;       Test.startTest(); try     {     updateCaseRecord.updateCheck(newCase1.Id);     List&lt;Case&gt; lCases = [SELECT Id,Status,OwnerId FROM Case WHERE Id =: newCase1.Id];     System.assertEquals('Closed', lCases[0].Status);      System.assertEquals(UserInfo.getUserId(), lCases[0].OwnerId);     }      catch(DMLException e) {         System.assertEquals(e.getMessage(), e.getMessage());     }      Test.stopTest();    }}   I thought I captured the try catch but when I run the test class it has only 57% code coverage and shows like below    Following one of the answers here
29653
I know Googling I can find an appropriate answer, but I prefer listening to your personal (and maybe technical) opinions. What is the main reason of the difference between Java and C# in throwing exceptions? In Java the signature of a method that throws an exception has to use the "throws" keyword, while in C# you don't know in compilation time if an exception could be thrown.
121895
I have a trigger and a class that seem to be causing an insert fail in Dataloader.  I am trying to insert 200 records to see if an error is generated before moving these to production. I'm just inserting the mandatory fields such as Name, Owner, Market, Customer_Success_Manager__c, and Business Unit.   Each time I get an error:     UpdateCSMTeam:execution of AfterInsertcaused by: System.DmlException:   Insert failed. First exception on row 0 with id01MJ0000009gXthMAE;   first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an   insert call: [Id]Class.UpdateCSM.updateTeamMem . I've listed the class   and trigger below.   APEX CLASS  public class UpdateCSM {             public static void updateTeamMember(List&lt;Account&gt; accounts) {                     List&lt;AccountShare&gt; ashareLIST = new List&lt;AccountShare&gt;();                     List&lt;AccountTeamMember&gt; ATM = new List&lt;AccountTeamMember&gt;();                    Set&lt;String&gt; rmMember = new Set&lt;String&gt;();                     Map&lt;ID, ID&gt; acctToBRepMap = new Map&lt;ID, ID&gt;();                      for(Account a:accounts){                              AccountShare caSharingRule = new AccountShare();                                caSharingRule.AccountId = a.Id;                                caSharingRule.OpportunityAccessLevel = 'Edit';                                caSharingRule.CaseAccessLevel = 'Edit';                                caSharingRule.AccountAccessLevel = 'Edit';                                caSharingRule.UserOrGroupId = a.Customer_Success_Manager__c;                                ashareLIST.add(caSharingRule);                                    if(a.Customer_Success_Manager__c!= null){                                   AccountTeamMember Teammemberad=new AccountTeamMember();                 Teammemberad.AccountId=a.id;                 Teammemberad.UserId=a.Customer_Success_Manager__c;                 Teammemberad.TeamMemberRole = 'Customer Success Manager';                                   ATM.add(Teammemberad);                             if(!ATM.isEmpty()){                                    insert ATM;                                              insert ashareLIST;                                                         if(a.Customer_Success_Manager__c==null){                                            list&lt;AccountTeamMember&gt; ratm = [SELECT UserId                                                                             FROM AccountTeamMember                                                                             WHERE (TeamMemberRole = 'Customer Success Manager')                                                          AND AccountId =:a.id];                                             if(ratm.size()&gt;0)                                                 delete ratm;                                        }                                    }                                 }                            }                         }                    } ...   APEX TRIGGER  trigger UpdateCSMTeam on Account (After update, After insert){         UpdateCSM.updateTeamMember(trigger.new); }
28494
I have an apex class which fetches and upserts data from external source to Salesforce. Below is the batch class: global class PolicyCalloutBatchClass implements Database.Batchable&lt;Integer&gt;,Database.AllowsCallouts, Database.Stateful {     global Iterable&lt;Integer&gt; start(Database.BatchableContext context) {         Integer[] values = new Integer[0];         while(values.size() &lt; 2999 || Test.isRunningTest()) values.add(values.size());         return values;     }     global void execute(Database.BatchableContext context, Integer[] values) {                  HttpRequest policyreq = new HttpRequest();         policyreq.setMethod('GET');         policyreq.setTimeout(120000);         policyreq.setEndpoint('&lt;endpoint&gt;');         policyreq.setHeader('Authorization', 'Bearer ' + &lt;token&gt;);         Http policyhttp = new Http();         HTTPResponse policyres = policyhttp.send(policyreq);         String policyresponse = policyres.getBody();         JsonParser objJsonParser = (JsonParser) JSON.deserialize(policyresponse, JsonParser.class);                    JsonParser.cls_value clsValue = objJsonParser.value;         Map&lt;String, JsonParser.cls_data&gt; clsDataMap = new Map&lt;String, JsonParser.cls_data&gt;();         for(JsonParser.cls_data objClsData: clsValue.data){             clsDataMap.put(objClsData.id, objClsData);         }         list&lt;Policy__c&gt; updatelist = new list&lt;Policy__c&gt;();         for (String eachIdFromMap : clsDataMap.keySet()){                          Policy__c policy = new Policy__c(                 unique_id__c = clsDataMap.get(eachIdFromMap).id,                 agent_id__c = clsDataMap.get(eachIdFromMap).agentId);             updatelist.add(policy);           }         try{             upsert updatelist unique_id__c;             }         catch(DmlException e){             system.debug('This class didnt compile');         }     }     global void finish(Database.BatchableContext context) {              } }  Below is my Mock test class: @isTest global class MockHttpResponseGenerator implements HttpCalloutMock {     // Implement this interface method     global HTTPResponse respond(HTTPRequest req) {           HttpRequest policyreq = new HttpRequest();         policyreq.setMethod('GET');         policyreq.setTimeout(120000);         policyreq.setEndpoint('&lt;endpoint&gt;');         policyreq.setHeader('Authorization', 'Bearer ' + &lt;token&gt;);         Http policyhttp = new Http();         HTTPResponse policyres = policyhttp.send(policyreq);         String policyresponse = policyres.getBody();                         return policyres;     } }  Below is my test class: @isTest  private class PolicyUpdateController_Test {     static testMethod void testPostCallout() {         Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());                    Test.startTest();       Database.executeBatch(new PolicyCalloutBatchClass(), 50);          Test.stopTest();              } }  Now, when I run the above test class, either the test class runs forever without any output or I could see the error as  System.LimitException: Too many callouts: 101  Can anyone please let me know if there is any way to get this done? Thanks!
16584
would report a violation for:  ArrayList&lt;Object&gt; list = new ArrayList&lt;Object&gt;();   The violation was "Avoid using implementation types like 'ArrayList'; use the interface instead".  The following line would correct the violation:  List&lt;Object&gt; list = new ArrayList&lt;Object&gt;();   Why should the latter with List be used instead of ArrayList?
113486
I am getting an exception of System.CalloutException: You have uncommitted work pending. Detail of the Exception is given Below:     Exception: :System.CalloutException: You have uncommitted work   pending. Please commit or rollback before calling out   I am using Apex for calling a Webservice. Based on the data returning from the WebService, performing upsert operation in Salesforce Instance. I am performing the following operation on the Salesforce Instance.  1 Performing upsert operation in Campaign Object.  2 Performing upsert Operation in Account Object.  3 Performing upsert Object in Contact Object using AccountID of the earlier inserted Account.  4 Then Adding Contacts as CampaignMember in the Campaign that I have Created earlier.  My code is working fine when There is only one record in the Webservice API but when there are more than one record in the API then getting the Exception of System.CalloutException: You have uncommitted work pending. I have spend one week but did not able to get rid off the exception.  Any help will be much appreciated.  Thanks in advance.
91232
I have created an app that would change CampaignMemeber Status Values by calling our web application api and storing info in custom objects. In my developer org where the package is created works fine but on our clients sandbox they get the error      System.QueryException: Non-selective query against large object type   (more than 200000 rows).   I know the reason that they get is because the query is not selective or that they have a lot of record. The error is occurring in a trigger. Below i have my trigger. Could anyone suggest a way to make my query more selective(i know about indexed field and tire that already) or any other way around the issue?    trigger SynchronizeTrigger on Attendee__c (after update, after insert) {      Map&lt;String,String&gt; matchedRegistration = new Map&lt;String,String&gt;();      Map&lt;String,String&gt; matchedCheckin = new Map&lt;String,String&gt;();      Set&lt;String&gt; matchedEmails = new Set&lt;String&gt;();      Map&lt;String,String&gt; matchedSurnames = new Map&lt;String,String&gt;();      CampaignMember[] cmList = new CampaignMember[]{};      List&lt;Fail__c&gt; flist = new List&lt;Fail__c&gt;();        Public Authentication__c auth = new Authentication__c();     auth = [SELECT Authentication_Campaign__c FROM Authentication__c LIMIT 1];        public Integer attendeesAttended = 0;     public Integer attendeesDidNotShow = 0;     public Integer attendeesAccepted= 0;     public Integer attendeesCancelled = 0;     public Integer attendeesfailed = 0;      for(Attendee__c a : Trigger.new){         matchedRegistration.put(a.Attendee_Email_Address__c,a.Attendee_Registration__c);         matchedCheckin.put(a.Attendee_Email_Address__c,a.Attendee_Checkin__c);          matchedEmails.add(a.Attendee_Email_Address__c);     }       for(List&lt;CampaignMember&gt; cms : [SELECT Id,Campaign.Id, Contact.Email,Status                            FROM CampaignMember                            WHERE  Campaign.Id =: auth.Authentication_Campaign__c AND  Contact.Email  IN: matchedEmails]){         for(CampaignMember cm : cms){            if(matchedRegistration.get(cm.Contact.Email)=='1' &amp;&amp; matchedCheckin.get(cm.Contact.Email)=='1'){                cm.Status = 'Attended';               cmList.add(cm);               attendeesAttended++;            }else if(matchedRegistration.get(cm.Contact.Email)=='1' &amp;&amp; matchedCheckin.get(cm.Contact.Email)=='0'){                cm.Status = 'Did Not Show';               cmList.add(cm);               attendeesDidNotShow ++;             }else if(matchedRegistration.get(cm.Contact.Email) =='1' &amp;&amp; String.isEmpty(matchedCheckin.get(cm.Contact.Email))){                cm.Status = 'Accepted';               cmList.add(cm);               attendeesAccepted ++;            }else if(matchedRegistration.get(cm.Contact.Email)=='0'){                cm.Status = 'Cancelled';               cmList.add(cm);               attendeesCancelled ++;                 }      update cmList;       }     }     for(List&lt;CampaignMember&gt; cms : [SELECT Id,Campaign.Id,FirstName,LastName,Contact.Email                            FROM CampaignMember                            WHERE Campaign.Id =: auth.Authentication_Campaign__c AND Contact.Email NOT IN: matchedEmails]){              for(CampaignMember cm : cms){              fList.add(new Fail__c(Fail_Firstname__c = cm.FirstName, Fail_Surname__c = cm.LastName, Fail_Email__c = cm.Contact.Email,Fail_Campaign_Name__c = cm.Campaign.Name ,Fail_Campaign__c = auth.Authentication_Campaign__c));             attendeesfailed ++;             upsert fList Fail_Email__c;           }   }     ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Confirm, 'Attended: ' + attendeesAttended + ' Delegate(s)' + ', ' + 'Did Not Show: ' + attendeesDidNotShow + ' Delegate(s)'+ ', ' + 'Accepted: ' + attendeesAccepted + ' Delegate(s)' + ', ' + 'Cancelled: ' + attendeesCancelled + ' Delegate(s)'));   ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 'Failed Syncs: ' + attendeesfailed + ' Delegate(s)')); }   Thanks
49131
I'm playing with a trigger exercise, that consists of creating a trigger to create 10 Opportunities whenever a account with more than 100 employees are created. I made the following: trigger AccountTrigger on Account (after insert) {     List&lt;Contact&gt; Contacts = new List&lt;Contact&gt;();     for (Account acct : Trigger.new){                for(integer i = 0; i &lt; 2; i++){             Contact cont    = new Contact();             cont.LastName   = acct.Name+ i;             cont.AccountId  = acct.Id;             Contacts.add(cont);         }         insert Contacts;      if (acct.NumberOfEmployees &gt; 99){         List&lt;Opportunity&gt; Opportunities = new List&lt;Opportunity&gt;();         for(integer i = 0; i &lt; 10; i++){             Opportunity opp = new Opportunity();             opp.Name        = acct.Name + i;             opp.CloseDate   = system.today()+ 30;             opp.StageName   = 'Open';             opp.AccountId   = acct.Id;             Opportunities.add(opp);         }         insert Opportunities;     }                      }  }   And I'm getting the following error: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATES_DETECTED, Use one of these records?:  I didn't created any, or changed the dupe rule of account neither Opportuinities. Can you help me understand what kind of error is this? And how can I change the trigger to workaround it? Thanks in advance!!
16290
This is a canonical question and answer developed by the community to help address common questions. If you've been directed here, or your question has been closed as a duplicate, please look through the resources here and use them to shape more specific questions. To browse all canonical questions and answers, navigate to the  tag. This question and answer is owned by the community! If you can improve it and make it more useful, you're welcome to edit it. I am building a trigger, a unit test, or other Apex code. I'm working with sObject records, and trying to access related record information. For example, I might have a structure like this: Account a = new Account(Name = 'Test'); insert a;  Opportunity o = new Opportunity(Name = 'Donation', AccountId = a.Id); insert o;  System.assertEquals(o.Account.Name, 'Test', 'Correct Account associated'); // Assertion fails!  Or, in a trigger, I might be aiming for something like this: trigger ContactTrigger on Contact (after insert) {     for (Contact c : Trigger.new) {         if (c.Account.Name == 'Test') {             // Take some action here         }      } }  Why doesn't this work? Why am I getting null values, or NullPointerExceptions?
55755
We are seeing this error in a Winform application.  Can anyone help on why you would see this error, and more importantly how to fix it or avoid it from happening.   System.ComponentModel.Win32Exception: Error creating window handle.    at System.Windows.Forms.NativeWindow.CreateHandle(CreateParams cp)    at System.Windows.Forms.Control.CreateHandle()    at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)    at System.Windows.Forms.Control.CreateControl()    at System.Windows.Forms.Control.OnVisibleChanged(EventArgs e)    at System.Windows.Forms.ButtonBase.OnVisibleChanged(EventArgs e)