I have an android app that l am busy with but ran into a small problem. I am trying to refresh/restart my fragement after saving data by the use of the save button but l am getting the following err:     Attempt to invoke virtual method 'void android.support.v4.app.Fragment.setNextAnim(int)' on a null object reference   here is my code in the button:      save1.setOnClickListener(new View.OnClickListener(){     @Override     public void onClick(View v) {         //Util.displayMessage(getContext(),"Saving");         String textToStore = contact1.getText().toString();         String textToStore2 = contact2.getText().toString();         String Url = "/gps/savetaxiroutes/"+imei+"/"+textToStore+"/"+textToStore2 +"/"+ sendNotification.toString()  ;          AllContacts fragment = (AllContacts)                  getFragmentManager().findFragmentById(R.id.thelayout2)          getFragmentManager().beginTransaction()                 .detach(fragment)                 .attach(fragment)                 .commit();         mPopupWindow.dismiss();     }     });   this is how the code is structured in my save button method.
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?
23661
Context Around this Code: I am making a schedulable class run each Sunday to track a couple of metrics important to the team.   Question: I am looking to consolidate DML operations and a big part of this is understanding pass by reference vs pass by value.  I want to pass the salesOps user object to the method SDREfficiencyLastWeek. I made the return type void, because I figured that I will be passing this by reference and I can make all the updates in the method without having to anything.   Why I am confused:    I read the above article and am thrown off by the following statement:  "Non-primitive data type arguments, such as sObjects, are also passed into methods by value. "   If the object is indeed passed by reference, then the query for the salesOps user in my code should be sufficient enough to edit all fields on that object without actually having to state each field in the query.  global class SDREfficientMetricsSchedulable implements Schedulable  {     global void execute(SchedulableContext sc)      {         User salesOps = [SELECT ID FROM USER WHERE id = '0056A000002Z3p9QAC'];         List&lt;String&gt; queries = new List&lt;String&gt;();          String contactsWorked_lastWeek  = 'select count(id) results from contact where LastActivityDate = last_week';         queries.add(contactsWorked_lastWeek);          String demosSet_lastWeek            = 'select count(id) results from form__c where CreatedDate = last_week';         queries.add(demosSet_lastWeek);          String demosCompleted_lastWeek  = 'select count(id) results from opportunity where (stagename = \'Unqualified Demo Completed\'  OR stagename = \'Qualified Demo Completed\' )  and RecordTypeId = \'0126A000000yudDQAQ\' and CloseDate = last_week';         queries.add(demosCompleted_lastWeek);          String qualifiedDemos_lastWeek  = 'select count(id) results  from opportunity where RecordTypeId = \'0126A0000004Ao6QAE\' and isclosed = false and  SDR_Owner__c != null and CreatedDate = last_week';         queries.add(qualifiedDemos_lastWeek);          String closedWon_lastWeek       = 'select count(id) results  from opportunity where RecordTypeId = \'0126A0000004Ao6QAE\' and iswon = true and  SDR_Owner__c != null and CloseDate = last_week';         queries.add(qualifiedDemos_lastWeek);            SDREfficiencyLastWeek(queries, salesOps);          update salesOps;     }       public void SDREfficiencyLastWeek(List&lt;String&gt; queries, User salesOps )     {        }  }
45746
I am trying to use following apex class with invocable method but its not showing in process builder.  global with sharing class SlackOpportunityPublisher {      private static final String slackURL = 'https://testsalesforceapps.slack.com/';      global class Oppty {         @InvocableVariable(label='Opportunity Name')         global String opptyName;         @InvocableVariable(label='Stage')         global String stage;     }      @InvocableMethod(label='Post to Slack')     global static void postToSlack(List&lt;Oppty&gt; oppties) {         Oppty o = oppties[0]; // If bulk, only post first to avoid overloading Slack channel         Map&lt;String,Object&gt; msg = new Map&lt;String,Object&gt;();         msg.put('text', 'The following opportunity has changed:\n' + o.opptyName + '\nNew Stage: *' + o.stage + '*');         msg.put('mrkdwn', true);         String body = JSON.serialize(msg);             System.enqueueJob(new QueueableSlackCall(slackURL, 'POST', body));     }      global class QueueableSlackCall implements System.Queueable, Database.AllowsCallouts {          private final String url;         private final String method;         private final String body;          global QueueableSlackCall(String url, String method, String body) {             this.url = url;             this.method = method;             this.body = body;         }          global void execute(System.QueueableContext ctx) {             HttpRequest req = new HttpRequest();             req.setEndpoint(url);             req.setMethod(method);             req.setBody(body);             Http http = new Http();             HttpResponse res = http.send(req);         }      }  }
89434
I am calling, through reflection, a method which may cause an exception. How can I pass the exception to my caller without the wrapper reflection puts around it? I am rethrowing the InnerException, but this destroys the stack trace. Example code:  public void test1() {     // Throw an exception for testing purposes     throw new ArgumentException("test1"); }  void test2() {     try     {         MethodInfo mi = typeof(Program).GetMethod("test1");         mi.Invoke(this, null);     }     catch (TargetInvocationException tiex)     {         // Throw the new exception         throw tiex.InnerException;     } }
61126
I am getting java.lang.NullPointerException while executing my test case , I am using Page Object Modle with PageFactory ,following are the code snippets  LoginPageObjec.java  public class LoginPageObjects {      @FindBy(xpath=".//*[@id='userName']")     private WebElement email;      @FindBy(xpath=".//*[@id='password']")     private WebElement password;      @FindBy(xpath=".//*[@id='loginFormSubmit']")     private WebElement loginBtn;      public void EnterUserName(String userName)     {         email.sendKeys(userName);     }      public void EnterPassword(String pass)     {         password.sendKeys(pass);     }      public void clickLogin()     {         loginBtn.click();     }   }   LoginTC.java  public class LoginTC extends BasePage{     private WebDriver driver;      @Test     public void login()     {         LoginPageObjects loginPage = PageFactory.initElements(driver, LoginPageObjects.class);         loginPage.EnterUserName("test.hr@domin.com.pk");         loginPage.EnterPassword("test");         loginPage.clickLogin();     } public void login1()         {             LoginPageObjects loginPage = PageFactory.initElements(driver, LoginPageObjects.class);             loginPage.EnterUserName("test.hr@domin.com.pk");             loginPage.EnterPassword("test");             loginPage.clickLogin();         }  }   BasePage.java  public class BasePage {     private WebDriver driver;      @BeforeMethod       public void initializeBrowser() {      driver=new FirefoxDriver();      driver.navigate().to("https://nexthrm-dev.vteamslabs.com/");      driver.manage().window().maximize();      }     @AfterMethod     public void closeBrowser()     {         driver.close();     }  }   I've extended BasePage class to utilize the (initialBrowser &amp; closeBrowser) functions in my test case but its producing nullpointer exception if I copy both of the functions (initialBrowser &amp; closeBrowser) into my LoginTC (testcase class) it works like charm but I dont want this redundant code i.e((initialBrowser &amp; closeBrowser) for all my testcases class could anyone explain why I am getting nullpointer exception
57448
So, I've been spending considerable more time on SO recently than I normally have, and one thing that I've noticed is quite a few people saying stuff like "There's a Null Pointer Error in this block of code, please help me fix it", with a huge amount of code posted, and no real clue as to where the NPE is. So my question is, what can we do to accomplish 2 goals?   Help the person asking the question become a better programmer. Help them to solve their problems.
22246
@AuraEnabled(cacheable=true) public static String  deleteContacts(List&lt;String&gt; contactIds) {     List&lt;Contact&gt; returnList = new List&lt;Contact&gt; ();     String query = ' SELECT Id,Name, LastName,Department,MobilePhone, Email FROM Contact WHERE id IN : contactIds ';     for (Contact thisContact:  Database.Query(query)) {          returnList.add(thisContact);     }     try {       delete returnList;       return'deleted successfully';     }     catch(Exception ex){        return 'Problem occoured';     }  }  JS Method deleteSelected(){     deleteContacts({         contactIds :this.selectedIds     })      .then(result =&gt; {         this.dispatchEvent(             new ShowToastEvent({                 title: 'Success',                 message: result,                 variant: 'success',             }),         );         return refreshApex(this.getContactList, { searchKeyWord: '$searchKeyWord' });     })     .catch(error =&gt; {         this.error = error;     });
97199
I am going through the documentation found here SF Lightning Guide, and during the portion where they create the Contact List view on page 36 they cover the click event using the built in force namespace action: navigateToURL. No matter what I try - $A is null. I have debug enabled, and can see that the line immediately before that call is working fine, and receives the ID of the record for the component, but $A is always coming back null.  I have tried e.force, e.., e.c., etc and cant imagine that this is normal. Everything else has been pretty smooth - but then this came along and I have spent several hours looking for anyone experiencing the same thing. This is a last resort before I scrap both this component and the one above it and start again from scratch.  Error being thrown is:      Uncaught error in markup://ui:click : Cannot read property 'setParams'   of null   I am using the exact code from the document at this time. Any ideas to try appreciated.  The code below is being called when a user clicks on a ui:outputText.  The sObjectEvent variable is always null.   I am wondering why it is always null - I assume the force namespace is always available.   gotoRecord : function(component, event, helper) { // Fire the event to navigate to the contact record     var sObjectEvent = $A.get("e.force:navigateToSObject");     sObjectEvent.setParams({         "recordId": component.get("v.contact.Id"),         "slideDevName": 'related'     })     sObjectEvent.fire(); }   EDIT:   Not able to comment yet - Tried adding &lt;aura:dependency resource="markup://force:navigateToSObject" type="EVENT"/&gt; to the component and now the error is gone, but nothing happens when you click the text either.    Developer Console is showing that the Event is now being picked up, and that the Params are set properly - $fired$ is true, and the params contains recordId properly now.  I will play with moving some controls around and switching it from a ui:outputText to something else.  Thank you for the responses.
94823
I am trying to create a button which will update a field value to null (RESET it). However, it's not working and not even giving any error. So when I click on the button, nothing happens.  lc.cmp:  &lt;aura:attribute name="myObj" type="Account" default="{'SObject':'Account'}"/&gt; &lt;lightning:input type="text" name="accountPhn" label="Enter Account Phone" value="{!v.myObj.Name}"/&gt; &lt;lightning:button label="Reset" onclick="{!c.resetMe}"/&gt;   lc.js:  resetMe : function(component, event, helper) {         //alert("Called");         component.set("v.accountPhn","");     }   Appreciate help around this.
96480
:     What should I do, if the "Open Call Hierarchy" is broken (empty for every method in a project)? It is very useful for code navigation, do not know, how to work without it!    (now converted to a comment):     I have had the same issue. Closing and re-opening the project fixed this issue for me. You might want to give that a try.   The comment on the answer (before it was deleted):     This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient reputation you will be able to comment on any post
49085
I am facing difficulty in passing parameters to apex method from test method. In apex method, I am getting parameters from my VF page. Example of Apex Method: public PageReference create_contact()  {         String callfrom = System.currentPageReference().getParameters().get('callfrom');                  Contact newCon = new Contact(lastname = 'Anonymous', phone = callfrom);           insert newCon;                  return null; }  My Test method: static testMethod void testmatchingcontactController() {         test.startTest();         matching_contacts mc = new matching_contacts();         mc.create_contact();         test.stopTest(); }  On running test method, I get an error that &quot;Argument cannot be null&quot; because the parameter callfrom in apex code is provided by Visualforce page in application. I don't know how can I pass it from test method. Please help if you know solution to this problem.
8114
I have same exception can please   The previous post issue is resolved.  Exception: :System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out  Visualforce Page   &lt;apex:page controller="Controller" action="{!init}" showHeader="false" sidebar="false"&gt;     &lt;center&gt;         &lt;apex:pageBlock title="Request Listener"&gt;&lt;/apex:pageBlock&gt;               &lt;/center&gt; &lt;/apex:page&gt;   Controller :            PUBLIC with sharing class Controller {        PUBLIC String fromNumber      = ApexPages.currentPage().getParameters().get('From');     PUBLIC String toNumber        = ApexPages.currentPage().getParameters().get('To');     PUBLIC String body            = ApexPages.currentPage().getParameters().get('Body');        PUBLIC PageReference init()     {                    System.debug('From Phone Number :' +fromNumber);         System.debug('To phone NUmber :' + toNumber);         System.debug('Message Body :' + body);          TwilioRestClient Client = TwilioAPI.getDefaultClient();                                                                SYSTEM.DEBUG('FROM AND To  Number is NOT NULL');                      String formattedNumber='+919876543210';                 IF(body != NULL)                 body = body;             ELSE                 body = '';             Case c = NEW Case (Subject = formattedNumber,Description = body,Origin = 'Phone');             INSERT c;                               Map&lt;String,String&gt; params1 = new Map&lt;String,String&gt;             {                'To'   =&gt; fromNumber,                'From' =&gt; '+1908280****',                'Body' =&gt; 'Conformation to customer'             };             TwilioMessage message = client.getAccount().getMessages().create(params1); /* Valid conformation SMS sent to the Customer.*/                                            return null ;     } }   While loin as admin then click preview on visualforce page executed but case is not created.I have checked the the debug log it throw the exception.
62103
Are there a way to add callback after the user created a record and clicked the Save button?  I am using a custom tab and custom components and open the Create a record modal window using e.force:createRecord, but I was not able to find out how to attach callback to the event.  I even found :     Currently force:createRecord event does not accept any callback method or any after save event to handle custom action. Current force:createRecord always redirects to the newly created record. But in case if you want to just close the force:createRecord popup after save and refresh some other related component using the refresh is not possible.    So, is it really impossible? If so, what are current workarounds here?
1271
We have a community built with custom lightning components and the locker service update is active. The onclick event has been defined on several components. The onclicks are working fine in Chrome, Firefox and IE11.   &lt;a href="" onclick="{!c.updateUser}"&gt;Save&lt;/a&gt;   There seem to be some issues in MS Edge though. When we click on an element with an onclick defined, we get the following error:     This page has an error. You might just need to refresh it. Error in $A.getCallback() [Unable to get property 'apply' of undefined or null reference] Failing descriptor: {markup://aura:html}    We have been testing on 5 different laptops. 3 of them have the error, while the other 2 don't have the issue in Edge. This was all tested in a Spring 17 sandbox. We also tested on a Winter 17 org with one of the laptops that has the issue and then everything seems to work fine.  Another test we did, was to remove all of the logic within the controller method and just have a console.log in it, but it never reached that point of the code since we didn't get the log. We also replaced the expression for the onclick with an alert, but that also doesn't work.  Does anyone have an idea how we can resolve this?
120685
It seems to me that a lot of my debugging time is spent chasing down null-reference exceptions in complex statements. For instance:  For Each game As IHomeGame in _GamesToOpen.GetIterator()   Why, when I get a NullReferenceException, can I get the line number in the stack trace, but not the name of the object that equals null. In other words, why:  Object reference not set to an instance of an object.   instead of  _GamesToOpen is not set to an instance of an object.   or  Anonymous object returned by _GamesToOpen.GetIterator() is null.   or  game was set to null.   Is this strictly a design choice, meant to protect the anonymity of the code or is there a compelling reason in compiler design not to include this information in the debug-time exception?
68276
In my page constructor I call a method isFirstPageLoaded, to  check if the loaded page is the first page of the wizard.   private final PageReference FIRSTPAGE = Page.Maintenance_Lock_1;   private void isFirstPageLoaded() {          if(ApexPages.currentPage()!=this.FIRSTPAGE) {              throw new MaintenanceLockException(this.FIRSTPAGE + ' --- ' + ApexPages.currentPage());          }      }   The problem is: Even if I open the first page of the wizard, the exception is thrown. How can I compare two PageReferences? I would like to avoid to parse the URLs and remove parameters etc...
90240
I have the below code:  public class CallOutForGet {      HttpRequest request=new Httprequest(); http http=new http(); request.setEndPoint('https://th-apex-http-callout.herokuapp.com/animals'); request.setmethod('GET');  HttpResponse response=http.send(request);  if(response.getStatusCode()==200){      Map&lt;String,Object&gt; results= (Map&lt;String,Object&gt;)JSON.deserializeUntyped(response.getBody());      List&lt;object&gt; animals=(List&lt;object&gt;)results.get('animals');     System.debug('Received Animals************');     for(object anim:animals){         System.debug(anim);     } }  }   This error at line -  request.setEndPoint('https://th-apex-http-callout.herokuapp.com/animals');  says expecting right parenthesis.