I'm running Spinx voice recognition as a thread and want to pass the result to a bot method mirroring the same method in Main to pass text. However keep running into NullPointerExpection and can't reason it out or overcome it. Why does it work in Main but not in Reply class.   the text send button in Main is:  private void onSend(java.awt.event.ActionEvent evt) {                                 // display users message         txtHistory.setText(txtHistory.getText() + "\nYou: " + txtMessage.getText() + "\n");          //send the input to the bot and get bot response         String response = bot.send(txtMessage.getText());          //if the response is not empty show it         if (response.length() &gt; 0) {         addBotText(response);         }            //display new state message to continue         addBotText(bot.getMessage());             //clear the input message box        txtMessage.setText("");    }   In the Runnable (Threaded) Spinx Reply class i have a method to get the voice input and then show it as a string:      private void start_recognition(Result result) {              if (result != null) {                 String resultText = result.getBestFinalResultNoFiller();                 //send the message to the bot                 String response = bot.send(resultText);                 System.out.println("You said: " + resultText + '\n');             } else {                 System.out.println("I can't hear what you said.\n");         }    }   (With private Bot bot; commented above in both Main and Reply) When I comment the String response = bot.send(resultText); out all is well, but trying to invoke the bot.send method creates a nullPointerException. I realize I'm doing something incredibly stupid but can't figure it out. The Bot method is below. Any help greatly appreciated.  In Bot class the send method:     public String send(String message) {      String response = "";     State state = parser.getState(level);      // end of the tree     if (state.getKeywords().isEmpty()) {         this.level = "1";     }      // match the keyword with given message     Keyword match = parse(message, state.getKeywords());      // if no keyword is matched, display one of the invalid answers     if (match == null) {         response = parser.getInvalidAnswer();     } else {          // if match classname is provided, check to get the dynamic response         if (match.className.length() &gt; 0) {              // check for Weather dynamic response             if (match.className.equals("Weather")) {                 Weather weather = new Weather();                 response = weather.getResponse(match.arg);                 this.level = "1";             }             // check for News dynamic response             if (match.className.equals("News")) {                 News news = new News();                 response = news.getResponse(match.arg);                 this.level = "1";             }         } else {              // get the new state and return the new message             if (response.length() == 0) {                  this.level = match.target;                 state = parser.getState(level);                  // if it is end of the tree                 if (state.getKeywords().isEmpty()) {                     response = this.getMessage();                     this.level = "1";                  }             }         }     }     return response; }   All code for the conditional bot is credited to Majid Khosravi
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?
36484
I'm trying to implement a KeyListener for my JFrame. On the constructor, I'm using this code:  System.out.println("test"); addKeyListener(new KeyListener() {     public void keyPressed(KeyEvent e) { System.out.println( "tester"); }      public void keyReleased(KeyEvent e) { System.out.println("2test2"); }      public void keyTyped(KeyEvent e) { System.out.println("3test3"); } });   When I run it, the test message comes up in my console. However, when I press a key, I don't get any of the other messages, as if the KeyListener was not even there.  I was thinking that it could be because the focus is not on the JFrame and so they KeyListener doesn't receive any events.  But, I'm pretty sure it is.  Is there something that I am missing?
439
Consider:  namespace WindowsApplication1 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }          private void button1_Click(object sender, EventArgs e)         {             //int[] val = { 0, 0};             int val;             if (textBox1.Text == "")             {                 MessageBox.Show("Input any no");             }             else             {                 val = Convert.ToInt32(textBox1.Text);                 Thread ot1 = new Thread(new ParameterizedThreadStart(SumData));                 ot1.Start(val);             }         }          private static void ReadData(object state)         {             System.Windows.Forms.Application.Run();         }          void setTextboxText(int result)         {             if (this.InvokeRequired)             {                 this.Invoke(new IntDelegate(SetTextboxTextSafe), new object[] { result });             }             else             {                 SetTextboxTextSafe(result);             }         }          void SetTextboxTextSafe(int result)         {             label1.Text = result.ToString();         }          private static void SumData(object state)         {             int result;             //int[] icount = (int[])state;             int icount = (int)state;              for (int i = icount; i &gt; 0; i--)             {                 result += i;                 System.Threading.Thread.Sleep(1000);             }             setTextboxText(result);         }          delegate void IntDelegate(int result);          private void button2_Click(object sender, EventArgs e)         {             Application.Exit();         }     } }   Why is this error occurring?     An object reference is required for the nonstatic field, method, or property 'WindowsApplication1.Form1.setTextboxText(int)
12512
Here is my problem: I've got a dialog with some parameters that the user can change (via a spinner for example). Each time one of these parameters is changed, I launch a thread to update a 3D view according to the new parameter value.  If the user changes another value (or the same value again by clicking many times on the spinner arrow) while the first thread is working, I would like to abort the first thread (and the update of the 3D view) and launch a new one with the latest parameter value.  How can I do something like that?  PS: There is no loop in the run() method of my thread, so checking for a flag is not an option: the thread updating the 3D view basically only calls a single method that is very long to execute. I can't add any flag in this method asking to abort either as I do not have access to its code.
112048
Background  I'm using  to update some picklist values on the fly. (i.e. Every time a record is inserted/updated/deleted in Table A, I'm adding/subtracting picklist values into a MultiselectePicklist in table B).  Since,     An Apex trigger can execute a callout when the callout is invoked within a method defined as asynchronous: that is, defined with the @future keyword.   I implemented a method with the future annotation, and      For Apex code that is executed asynchronously, such as @future methods, Batch Apex jobs, or scheduled Apex jobs, getSessionId returns null.   so, I needed to pass the session Id as a parameter in the method, I implemented something like:  @future (callout=true) public static void addContactPicklistPreference(List&lt;String&gt; preferences, String sessionId){     Schema.DescribeSObjectResult sObjectDescribe = Contact.sObjectType.getDescribe();     String picklistFieldName = 'Preference__c';                    Picklist_MDT.addPicklistValues(sObjectDescribe, picklistFieldName, artists, sessionId); }  public class Picklist_MDT {      public static void addPicklistValues(Schema.DescribeSObjectResult sObjectDescribe, String picklistFieldName, List&lt;String&gt; picklistValueNames, String sessionId) {         MetadataService.MetadataPort service = createService(sessionId);         ...         }       public static MetadataService.MetadataPort createService(String sessionId) {         MetadataService.MetadataPort service = new MetadataService.MetadataPort();         service.SessionHeader = new MetadataService.SessionHeader_element();         service.SessionHeader.sessionId = sessionId;         return service;     } }   And called the addContactPicklistPreference method from trigger context passing it the UserInfo.getSessionId() value.   Problem  This worked just fine in salesforce classic but not in lightning, when it triggers in lightning I'm getting System.CalloutException: Web service callout failed: WebService returned a SOAP Fault: INVALID_SESSION_ID.... Funny thing is that if I put a System.debug(UserInfo.getSessionId()); before calling the addContactPicklistPreference method it prints a valid session Id in both classic and lightning.  I would really appreciate any input about this.
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.
90464
We noticed that lots of bugs in our software developed in C# (or Java) cause a NullReferenceException.  Is there a reason why "null" has even been included in the language?  After all, if there were no "null", I would have no bug, right?  In other words, what feature in the language couldn't work without null?
122495
I cannot figure out how to make a C# Windows Form application write to a textbox from a thread.  For example in the Program.cs we have the standard main() that draws the form:  static void Main() {     Application.EnableVisualStyles();     Application.SetCompatibleTextRenderingDefault(false);     Application.Run(new Form1()); }   Then we have in the Form1.cs:  public Form1() {     InitializeComponent();      new Thread(SampleFunction).Start(); }  public static void SampleFunction() {     while(true)         WindowsFormsApplication1.Form1.ActiveForm.Text += "hi. "; }   Am I going about this completely wrong?  UPDATE  Here is the working code sample provided from bendewey:  public partial class Form1 : Form {     public Form1()     {         InitializeComponent();         new Thread(SampleFunction).Start();     }      public void AppendTextBox(string value)     {         if (InvokeRequired)         {             this.Invoke(new Action&lt;string&gt;(AppendTextBox), new object[] {value});             return;         }         textBox1.Text += value;     }      void SampleFunction()     {         // Gets executed on a seperate thread and          // doesn't block the UI while sleeping         for(int i = 0; i&lt;5; i++)         {             AppendTextBox("hi.  ");             Thread.Sleep(1000);         }     } }
73868
I need help. I am currently trying to test this code before uploading  public class CoreValuesExt { ApexPages.StandardController sc; public boolean readonly {get; set;} public Core_Values__c cv {get; set;} public integer countEdit = 1; public string buttonValue {get; set;} public integer recordScan;  public CoreValuesExt(ApexPages.StandardController sc) {     this.sc = sc;     cv = new Core_Values__c();     cv.Account__c = sc.getid();      readonly = true;     buttonValue = 'Edit';     recordScan = [SELECT COUNT() FROM Core_Values__c WHERE Account__c = :cv.Account__c];    if (recordScan != 0){    cv = [SELECT id, HSE__c, Professionalism_Integrity__c, Quality_Accuracy__c, Technology_Innovation__c, Timeliness__c, Value_for_money__c FROM Core_Values__c WHERE Account__c = :cv.Account__c];     }  }  public ApexPages.PageReference Save() {     return sc.Save(); }  public void ApplyAction() {     countEdit++;     Integer modolus = Math.mod(countEdit, 2);     String total = cv.HSE__c + cv.Professionalism_Integrity__c + cv.Quality_Accuracy__c + cv.Technology_Innovation__c + cv.Value_for_Money__c + cv.Timeliness__c;     if(modolus == 0)     {         readonly = false;         buttonValue = 'Save';     }     else     {         if(total != 'nullnullnullnullnullnull')            {         if (recordScan == 0){         insert cv;         readonly = true;         buttonValue = 'Edit';         }         else         {         update cv;         readonly = true;         buttonValue = 'Edit';         }         }     }    }   }  With this trigger.  trigger CoreValuesTrigger on Core_Values__c (before insert) {  Core_Values__c cvs = Trigger.new; CoreValuesExt.ApplyAction(cvs);  }   But when I try to save, I get a message saying:      Illegal assignment from List to   CoreValuesExt__Core_Values__c at line 3 column 1   "  How do I go through with this? I need help. Thanks
111654
I just . Namely, the C++ function:  void returnCharPtr(char * someString, int n);   cannot return any CharPtr because the someString pointer is passed by value. Also, the intent of the author was clear:      So, another option is to pass the parameter as an argument, so you process your string in a function but don't create a new copy.   But as the change was rejected (3 vs 2) the post stayed in an incorrect state (IMHO).   I left a comment to the author. Can I argue with the editors' decision?
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 )     {        }  }
37897
There are situations, where it is practical to have a type-cast return a null value instead of throwing a ClassCastException. C# has the as operator to do this. Is there something equivalent available in Java so you don't have to explicitly check for the ClassCastException?
8665
I am trying to copy records from one org to other via web services. I am calling a class which has logic written into a trigger. But @ future method is not taking sObject  list as a parameter. Can someone suggest me an alternative?  The Code:  public class webServicesTriggerClass   {     @future public static void webServicesMethod(list&lt;MyFriend__c&gt; mfList)     {         partnerSoapSforceCom.Soap sp = new partnerSoapSforceCom.Soap();       partnerSoapSforceCom.LoginResult lr = sp.login('hitesh.kumar.singh@accenture.com.varun','4Rajyavardhan');      soapSforceComSchemasClassNiralaapp.SessionHeader_element ses = new soapSforceComSchemasClassNiralaapp.SessionHeader_element();      ses.sessionId = lr.sessionId;       soapSforceComSchemasClassNiralaapp.MyFriendsDetailSoapApi vNapp=new soapSforceComSchemasClassNiralaapp.MyFriendsDetailSoapApi();      for(MyFriend__c mf:mfList)       {        string  s1= mf.myEmail__c;        string  s2=mf.friendName__c;         string  s3=mf.friendEmail__c;        string  s4=mf.aboutFriend__c;        integer i1=Integer.ValueOf(mf.age__c);        boolean result=vNapp.addFriendDetails(s1,s2,s3,s4,i1);        system.debug('################' +result);           }     }    }     Trigger-->  trigger webServicesTrigger on MyFriend__c (after insert)     {      webServicesTriggerClass.webServicesMethod(trigger.new);    }     Error--    Error: Compile Error: Unsupported parameter type LIST at line 3 column 30
86546
I have been trying to integrate Google Shortener API into my salesforce org. I wrote a class to make the call out, but am having difficulty bringing the value back into the record. I have a custom object called "referral_advocate__c" with a field called "Short_URL__c". Anytime the field "unique_ID__c" has a value, I am wanting to send this value with a static URL to google shortener and then save the response value to "referral_advocate__c.short_URL__c" on the record. This is the class to make the call out:  public class URLshort {  final string urls = 'https://www.myurl.com'; referral_advocate__c adv = new referral_advocate__c();  @future(callout = true) public static void URLshortner() {      HttpRequest req = new HttpRequest();     HttpResponse res = new HttpResponse();     Http http = new Http();      req.setEndpoint('https://www.googleapis.com/urlshortener/v1/url?key=myapikey');     req.setMethod('POST');     req.setHeader('Content-Type','application/json');            req.setBody('{"longUrl":+urls + adv.unique_reference_number_c}');       try {         res = http.send(req);         System.debug(res.getBody());     } catch(System.CalloutException e) {         System.debug('Callout error: '+ e);         System.debug(res.toString());     }   }  }   The after insert trigger on "referral_advocate__c" I wrote is not firing correctly. How do I return the results from this class and update the field "short_URL__C" with the returned value from a trigger?
105367
I'm trying to develop my first test class in our sandbox instance. When running the below test, I am getting no records return from the first query to build accountsList. The test succeeds, but I have 0% code coverage. The trigger works as expected when ran.  My Test Class:  @isTest private class test_deleteAccountSharesOnUpdate {  static testMethod void updateAccounts()  {     Set&lt;String&gt; accountIds = new Set&lt;String&gt;();      List&lt;Account&gt; accountsList =      [         SELECT Id, Is_Script_Update__c, Description FROM Account     ];      Integer i = 0;     for (Account acct : accountsList)     {         if(i &gt; 199)         {             break;         }          acct.Is_Script_Update__c = True;         acct.Description = 'Testing at ' + System.now();          accountIds.add(acct.Id);          i++;     }      test.startTest();      update accountsList;      test.stopTest();      List&lt;Account&gt; updatedAccts =      [         SELECT Id, Is_Script_Update__c, Description         FROM Account          WHERE Id IN : accountIds     ];      for(Account acct : updatedAccts)     {         System.assertEquals         (             'Testing at',             acct.Description.substring(0,10)         );     } }   }  Trigger I'm trying to test:  trigger deleteAccountSharesOnUpdate on Account (after update)  {    Set&lt;String&gt; accountIds = new Set&lt;String&gt;();  // Gather the account Ids being updated for (Account acct : trigger.new) {     // Only remove shares for accounts being updated by data loader.     // Loader script will insert new shares after this job.     if(acct.Is_Script_Update__c)     {         String terrCode = acct.Territory_Code_String__c;          if(terrCode != null &amp;&amp; terrCode.length() == 5)         {                accountIds.add(acct.id);         }     } }  if(accountIds.size() &gt; 0) {     // Remove the shares associated with these accounts     delete      [         select id          from AccountShare          where RowCause = 'TerritoryManual' AND          AccountId IN : accountIds     ];      // Reset flag that indicates this update is from a data loader.     // Data loader will set this checkbox as true on update.     // This prevents the trigger on UI update.     //     List&lt;Account&gt; accountsList =      [         SELECT Id, Is_Script_Update__c          FROM Account          WHERE Id IN: accountIds     ];      for (Account acct : accountsList)     {         acct.Is_Script_Update__c = False;     }      update accountsList; }   }  Degub log shows no rows returned for the first query:  14:47:14.461 (3461430000)|SOQL_EXECUTE_BEGIN|[8]|Aggregations:0|select Id,       Is_Script_Update__c, Description from Account 14:47:14.483 (3483545000)|SOQL_EXECUTE_END|[8]|Rows:0  Any help is greatly appreciated!
109516
I'm trying to use the HTTP Callout methods provided in Apex to  1. Get a token from Marketo 2. Use this token to create three leads in Marketo using the REST API  However, it doesn't seem to be working. I have never coded something like this before, so I expect that I probably made some very embarrassing and obvious mistakes, but I've been able to find very little documentation on this, so I'm starting from basically scratch and the REST API documentation. Anyways, here's the two classes I've been using to attempt to do this:  Class 1:  global class MakeCallouts {       static String testCallout() {          HttpResponse res = CalloutClass.getInfoFromExternalService();         String contentType = res.getHeader('Content-Type');         System.assert(contentType == 'application/json');         System.assertEquals(200, res.getStatusCode());      //getting the accesstoken       String getToken;     String answer = res.getBody();     System.debug(answer);  JSONParser parser = JSON.createParser(answer); while (parser.nextToken() != null) {     if ((parser.getCurrentToken() == JSONToken.FIELD_NAME)){         String fieldName = parser.getText();         parser.nextToken();         if(fieldName == 'access_token') {            getToken = parser.getText();               }  } } System.debug(getToken);           HttpResponse res2 = CalloutClass.getInfoFromExternalService2(getToken);           String contentType2 = res2.getHeader('Content-Type');         System.assert(contentType2 == 'application/json');         System.assertEquals(200, res2.getStatusCode());          System.debug(res2.getBody());         return res2.getBody();     } }   Class 2:  public class CalloutClass {  public static HttpResponse getInfoFromExternalService () {     // Instantiate a new http object     Http h = new Http();       // Instantiate a new HTTP request, specify the method (GET) as well as the endpoint     HttpRequest req = new HttpRequest();     req.setEndpoint('https://XXX-rlu-923.mktorest.com/identity/oauth/token?grant_type=client_credentials&amp;client_id=XXXX&amp;client_secret=XXXX');     req.setMethod('GET');      // Send the request, and return a response     HttpResponse res = h.send(req);     return res;  }   public static HttpResponse getInfoFromExternalService2 (String getToken) {     // Instantiate a new http object     Http h2 = new Http();       // Instantiate a new HTTP request, specify the method (POST) as well as the endpoint     HttpRequest req2 = new HttpRequest();     req2.setHeader('Content-Type','application/json');      req2.setMethod('POST');     req2.setEndpoint('https://XXXX.mktorest.com/rest/v1/leads.json?access_token='+getToken);     req2.setBody('{"action":"createOnly","input":[{"email":"kjashaedd-1@klooblept.com","firstName":"Kataldar-1","postalCode":"04828"},{"email":"kjashaedd-2@klooblept.com","firstName":"Kataldar-2","postalCode":"04828"},{"email":"kjashaedd-3@klooblept.com","firstName":"Kataldar-3","postalCode":"04828"}]}}');      // Send the request, and return a response     HttpResponse res2 = h2.send(req2);     return res2;  }    }   The MakeCallouts class is triggered when a Lead is created (this is entirely for testing purposes. I'm going to change the API call after I get this to work. But it's pretty obvious that the call is working when I see three new leads appear in my database, so it's a good test).
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.