When I run the emulator, it woks perfectly with no errors, but when I press the Login button, I get error "java.lang.NullPointerException: Attempt to invoke interface method".  This is my code:  public class MainActivity extends ActionBarActivity {      Button add;     TextView errorlbl;     EditText name, address, pincode;     Connection connect;     PreparedStatement preparedStatement;     Statement st;     String ipaddress, db, username, password;      @SuppressLint("NewApi")     private Connection ConnectionHelper(String user, String password,                                         String database, String server) {         StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()                 .permitAll().build();         StrictMode.setThreadPolicy(policy);         Connection connection = null;         String ConnectionURL = null;         try {             Class.forName("net.sourceforge.jtds.jdbc.Driver");             ConnectionURL = "jdbc:jtds:sqlserver://" + server + ";"                     + "databaseName=" + database + ";user=" + user                     + ";password=" + password + ";";             connection = DriverManager.getConnection(ConnectionURL);         } catch (SQLException se) {             Log.e("ERRO", se.getMessage());         } catch (ClassNotFoundException e) {             Log.e("ERRO", e.getMessage());         } catch (Exception e) {             Log.e("ERRO", e.getMessage());         }         return connection;     }      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          add = (Button) findViewById(R.id.btnadd);          errorlbl = (TextView) findViewById(R.id.lblerror);          name = (EditText) findViewById(R.id.txtname);         address = (EditText) findViewById(R.id.txtaddress);         pincode = (EditText) findViewById(R.id.txtpincode);          ipaddress = "92.244.93.250:3306";         db = "lokal";         username = "lokal";         password = "12lokal34";         connect = ConnectionHelper(username, password, db, ipaddress);         add.setOnClickListener(new View.OnClickListener() {              @Override             public void onClick(View v) {                 try {                     st = connect.createStatement();                      preparedStatement = connect                             .prepareStatement("insert into studentRecord(Name,Address,Pincode) values ('"                                     + name.getText().toString()                                     + "','"                                     + address.getText().toString()                                     + "','"                                     + pincode.getText().toString() + "')");                     preparedStatement.executeUpdate();                     errorlbl.setText("Data Added successfully");                 } catch (SQLException e) {                     errorlbl.setText(e.getMessage().toString());                 }              }         });      } }   Logcat error says:       2182-2182/app.mysqlapp E/AndroidRuntime﹕ FATAL EXCEPTION: main       Process: app.mysqlapp, PID: 2182       java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.Statement java.sql.Connection.createStatement()' on a null object reference
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?
20439
I am trying to get this trigger to work but it is giving me an error and I am not able to figure out why. The error I am getting is "attempt to de-reference a null object)  Why trigger? We have a Destinations object which is linked to Supplier products object via a lookup relationship. There are two types of supplier products(marketplace and curated) We want to count the number of live Supplier products and put them in a separate fields(live counts for each type).  I have gotten so far to actually count the number of live products and it is giving me an error. Can any one help? I am posting the code below  Trigger code :   trigger NoOfLiveProducts on Supplier_Product__c (after insert, after Delete, after update, after undelete) {       set&lt;string&gt; destinationids = new set&lt;string&gt;();      if(trigger.isInsert) {         for(Supplier_product__c products : Trigger.new) {             destinationids.add(products.Destination__c);         }     } else if(trigger.isDelete) {         for(Supplier_product__c products : Trigger.old) {             destinationids.add(products.Destination__c);         }     }else if(trigger.isUnDelete) {         for(Supplier_product__c products : Trigger.new){             destinationids.add(products.Destination__c);         }      } else if(trigger.isUpdate) {         for(Supplier_product__c products : Trigger.new) {             destinationids.add(products.Destination__c);         }     }      if(destinationids.size() &gt; 0){         Productcounter pc = new Productcounter();         pc.updateproductCount(destinationids);     }    }   Class code :  public class Productcounter {      public void updateproductcount(set&lt;string&gt; productIDs) {           if(productIDs == null){                return;         }          if(productIDs.size() == 0){             return;         }           list&lt;Supplier_Product__c&gt; ProductList = new list&lt;Supplier_Product__c&gt;();         ProductList = [Select ID,Destination__c                     From Supplier_Product__c                     Where Destination__c = :productIDs];          integer totalCount;         map&lt;string, integer&gt; DestinationIDToProductCountMap = new map&lt;string, integer&gt;();                for(Supplier_product__c ProductItem : ProductList){             if(DestinationIDToProductCountMap.containsKey(ProductItem.Destination__c)){                 totalCount = DestinationIDToProductCountMap.get(ProductItem.Destination__c);             }else{                 totalCount = 0;             }             totalCount += 1;             DestinationIDToProductCountMap.put(ProductItem.Destination__c, totalCount);         }          list&lt;Destination__c&gt; DestinationUpdateList = new list&lt;Destination__c&gt;();         Destination__c DestinationTemp;         for(string ProductID : DestinationIDToProductCountMap.keySet()){             DestinationTemp.ID = ProductID;             DestinationTemp.No_of_Live_Curated_Products__c = DestinationIDToProductCountMap.get(ProductID);             DestinationUpdateList.add(DestinationTemp);         }         if(DestinationUpdateList.size() &gt; 0){             update DestinationUpdateList;         }           }           }
52784
This question appears to have been answered several times on here, but none of the solutions are working for me.  I have an Apex function defined like so:  @RemoteAction global static ActivityWrapper createActivity(Activity__c activity)   And when I call this Javascript function:  Controller.createActivity(     {ForWeek__c: "2014-04-21T08:00:00.000Z",      Notes__c: "sdfsdf",      Type__c: "Referral",      Id: null,      sObjectType: "Activity__c"}, callback);   I always get back this error message:  Visualforce Remoting Exception: Unexpected type for Controller.createActivity(Activity__c)   As far as I know this is all that is required, but I can't get past this.
93772
below is my code Created a wrapper class like below  public class ResponseWrapper{     public list&lt;Account&gt; lstaccounts;     public boolean isError ;     public string errorCode;     public integer statusCode;        public ResponseWrapper(){          lstaccounts = new list&lt;Account&gt;();          isError= false;     }  }   and returning the wrapper class in the Httpget method  @RestResource(urlMapping='/accounts/*') global with sharing class AccountRestService { @HttpGet global static ResponseWrapper getAccounts() {     ResponseWrapper resWrap = new ResponseWrapper();     List&lt;Account&gt; accounts;      try {         accounts = [SELECT Id, Name FROM Account];         res.lstaccounts = accounts;     } catch (Exception e) {         RestResponse res = RestContext.response;         resWrap.isError = true;         res.responseBody = Blob.valueOf(e.getMessage()) = resWrap.errorCode;         res.statusCode = 500 = resWrap.statusCode;     }      return resWrap;   } }   but its throwing the Error message  Error: Compile Error: global methods do not support return type of ResponseWrapper at line 4 column 31
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.
101111
We've had a community deployment and my brain is fried and I just whipped up a quick class that is throwing the below error. What have I done wrong here?     Error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, MSI_UserTrigger:   execution of AfterInsert caused by: System.StringException: Invalid   id: () : [] () : []: ()   What I am trying to accomplish is:   When a new user is created and is active, if they are linked to a ContactId and part of a specific profile (by name), add their ContactId to a Set&lt;ID> Then loop through contacts where the Id is in the set, and update the Community_User__c field to TRUE      Trigger:   trigger MSI_UserTrigger on User (after insert) {       if(Trigger.isAfter){          if(Trigger.isInsert){              MSIUserTriggerHandler.executeAfterInsert(Trigger.new);          }      } }      Class:   public with sharing class MSIUserTriggerHandler {     private static final String COMMUNITY_PROFILE = 'Community Knowledge User';     private MSIUserTriggerHandler() {}      public static void executeAfterInsert(List&lt;User&gt; newList){         setCreatedCommunityUsers(newList);     }      private static void setCreatedCommunityUsers(List&lt;User&gt; newList){         List&lt;User&gt; usersWithContacts = new List&lt;User&gt;();         List&lt;Contact&gt; contactsToUpdate = new List&lt;Contact&gt;();         Set&lt;ID&gt; contactIds = new Set&lt;ID&gt;();          for(User u: newList){             if(u.ContactId == null &amp;&amp; u.ContactId == ''){                 continue;             }             if((u.ContactId != null &amp;&amp; u.ContactId != '') &amp;&amp; u.Profile.Name == COMMUNITY_PROFILE &amp;&amp; u.isActive == true){                 contactIds.add(u.ContactId);             }         }          for(Contact c : [Select Id,Name,Community_User_Created__c from Contact where Id in :contactIds]){             if(!c.Community_User_Created__c){                 c.Community_User_Created__c = true;                 contactsToUpdate.add(c);             }         }         update contactsToUpdate;     } }   Am I not adding the ID correctly to the Set&lt;ID>, or am I querying wrong in my for(Contacts) loop?
77222
I have a really simple Java class that effectively decorates a Map with input validation, with the obvious void set() and String get() methods.  I'd like to be able to effectively call those methods and handle return values and exceptions from outside the JVM, but still on the same machine Update: the caller I have in mind is not another JVM; thanks @Dave Ray  My implementation considerations are typical    performance ease of implementation and maintenance (simplicity?) reliability flexibility (i.e. can I call from a remote machine, etc.)   Is there a 'right way?' If not, what are my options, and what are the pro/cons for each?  (Stuff people have actually done and can provide real-life feedback on would be great!)
72983
I have been struggling with this error for a few days now. I get this error every time I try to run a test for a method that has an httpCallout. I followed the architecture from  , but to no avail. I thought it could be something I was messing up in my code, so I copied all three of the classes from the documentation, and I am still getting the error when I try to run the test. All of the classes are on Salesforce API 29. Has anyone run into this before?
122316
I am trying to do this:   Below is the screenshot taken from eclipse  package com.stack.tests;  import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile;  public class PerformanceTesting {        public static void main(String[] args) {             FirefoxProfile profile = new FirefoxProfile();             WebDriver driver = new FirefoxDriver(profile);             driver.quit();         } }   Below is the error code taken while running:  E:\stackoverflow\src\test\java\com\stack\tests&gt;javac -cp selenium-serv er-standalone-2.52.0.jar PerformanceTesting.java  E:\stackoverflow\src\test\java\com\stack\tests&gt;set classpath=%classpat h%;.;  E:\stackoverflow\src\test\java\com\stack\tests&gt;java -cp .;selenium-ser ver-standalone-2.52.0.jar PerformanceTesting Exception in thread "main" java.lang.NoClassDefFoundError: PerformanceTesting (w rong name: com/stack/tests/PerformanceTesting)         at java.lang.ClassLoader.defineClass1(Native Method)         at java.lang.ClassLoader.defineClass(Unknown Source)         at java.security.SecureClassLoader.defineClass(Unknown Source)         at java.net.URLClassLoader.defineClass(Unknown Source)         at java.net.URLClassLoader.access$100(Unknown Source)         at java.net.URLClassLoader$1.run(Unknown Source)         at java.net.URLClassLoader$1.run(Unknown Source)         at java.security.AccessController.doPrivileged(Native Method)         at java.net.URLClassLoader.findClass(Unknown Source)         at java.lang.ClassLoader.loadClass(Unknown Source)         at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)         at java.lang.ClassLoader.loadClass(Unknown Source)         at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)   Does somebody know how to fix it?
105415
This is the test method i have writtenfor batch apex ProductUpdate  .Even if i have a single callout to Database.Executebatch()  I am getting the following error.  Please help !  @isTest (seeAllData=true) global class testbatchProductUpdate  {     public static testMethod  void  pBatchUpdate()     {          /** Product to meet the Criteria in test class **/          Product2 p = new Product2();         p.Name = 'Test Product';         p.Effective_Date__c = Date.Today();         //p.CurrencyIsoCode= 'USD';         p.Material_status__c='status';         insert p;          /** Product to meet the Criteria in test class **/           test.startTest();         batchProductUpdate bpu = new batchProductUpdate();         database.Executebatch(bpu);         test.stopTest();     }  }      Error :  System.UnexpectedException: No more than one executeBatch can be called from within a testmethod. Please make sure the iterable   returned from your start method matches the batch size, resulting in   one executeBatch invocation.", Failure Stack Trace: "External entry   point"
33203
What exception should I throw if I encounter an illegal state - for instance, an initialization method that should only be called once being called a second time?  I don't really see any built-in exception that makes sense.  This seems like something that should be in the framework - am I not poking in the right spot?
60003
I've got a few methods that should call System.exit() on certain inputs. Unfortunately, testing these cases causes JUnit to terminate! Putting the method calls in a new Thread doesn't seem to help, since System.exit() terminates the JVM, not just the current thread. Are there any common patterns for dealing with this? For example, can I subsitute a stub for System.exit()?   [EDIT] The class in question is actually a command-line tool which I'm attempting to test inside JUnit. Maybe JUnit is simply not the right tool for the job? Suggestions for complementary regression testing tools are welcome (preferably something that integrates well with JUnit and EclEmma).
34848
I used to use the implicit call of toString when wanting some debug info about an object, because in case of the object is null it does not throw an Exception.  For instance:    System.out.println("obj: "+obj);   instead of:  System.out.println("obj: "+obj.toString());   Is there any difference apart from the null case? Can the latter case work, when the former does not?  Edit: What exactly is done, in case of the implicit call?
8224
Since many users are facing the NullReferenceException: Object reference not set to an instance of an object error in Unity, I thought that it would be a good idea to gather from multiple source some explanation and ways to fix this error.  Symptoms I am getting the error below appearing in my console, what does it mean and how do I fix it?  NullReferenceException: Object reference not set to an instance of an object
109154
hi i am sending some data to controller method through action function using jquery. but in controller method i am getting null value, please help. i am getting a response from ajax method and then want to send that response to controller method through action function. using apex:param but getting null values in debug  visualforce page          &lt;apex:page controller="SendAgreementExt"&gt;   &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"&gt;&lt;/script&gt;    &lt;form id="data" method="post" enctype="multipart/form-data"&gt;      &lt;apex:pageBlock &gt;     &lt;apex:pageBlockSection showHeader="false" columns="2"&gt;     &lt;apex:pageBlockSectionItem &gt;         &lt;apex:outputLabel value="File Name" for="fileName" /&gt;    &lt;input type="text" name="File-Name" value="" /&gt;   &lt;input type="hidden" name="Mime-Type" value="application/pdf" /&gt;   &lt;/apex:pageBlockSectionItem&gt;   &lt;apex:pageBlockSectionItem &gt;   &lt;apex:outputLabel value="File" for="file" /&gt;  &lt;input name="File" type="file" /&gt;  &lt;/apex:pageBlockSectionItem&gt;  &lt;/apex:pageBlockSection&gt;    &lt;apex:pageBlockButtons &gt;         &lt;button&gt;Submit&lt;/button&gt;      &lt;/apex:pageBlockButtons&gt;         &lt;/apex:pageBlock&gt;      &lt;/form&gt;     &lt;script type="text/javascript"&gt;  $("form#data").submit(function(){   var formData = new FormData($(this)[0]);  $.ajax({ url: 'https://api.na1.echosign.com/api/rest/v5/transientDocuments', type: 'POST',     headers: {'Access-Token' :'3AAABLblqZhCG8fU-alud8zcDf-N8I68P7yfB6nIi6U_PcCQsnobiSYzIpfzmgYaCMnl2PwcuVlSbk7yS_uNV8BkF8ymc3f2m'}, data: formData, async: false, success: function (data) {      document.getElementById("myHiddendid").value = data.transientDocumentId;       myFun(data.transientDocumentId);     //SendAgreementExt.send(data); }, cache: false, contentType: false, processData: false  });    return false;  });  &lt;/script&gt;  &lt;apex:form &gt;  &lt;input type="hidden" value="{!documentid}" id="myHiddendid"/&gt;   &lt;apex:actionFunction name="myFun" action="{!send}"&gt;    &lt;apex:param name="myParam" value="" id="y" assignTo="{!documentid}" /&gt;    &lt;/apex:actionFunction&gt;   &lt;/apex:form&gt;  &lt;/apex:page&gt;   Controller       Public with Sharing Class SendAgreementExt   {   public string LeadMessage{get;set;}  public string documentid{get; set;} public string docid{get; set;}  public PageReference send() {     System.debug('VARIABLE documentid------' + documentid);                        documentid=Apexpages.currentPage().getParameters().get('documentid');    System.debug('VARIABLE documentid------' + documentid);   //system.debug('==in method');  string passedParam1 =Apexpages.currentPage().getParameters().get('myParam');  string passedParam2 =    system.CurrentPageReference().getParameters().get('myParam');   system.debug(passedParam1);   system.debug(passedParam2);     return null;               }      }
81630
Why does this test program result in a java.lang.IllegalMonitorStateException?  public class test {     static Integer foo = new Integer(1);     public static void main(String[] args) {         synchronized(foo) {             foo++;             foo.notifyAll();         }         System.err.println("Success");     } }   Result:  Exception in thread "main" java.lang.IllegalMonitorStateException         at java.lang.Object.notifyAll(Native Method)         at test.main(test.java:6)
120972
My application has javascript button that call Apex code.  Exceptions from web services are sometimes thrown and the user is shown a detailed exception message like this:  A problem with the OnClick JavaScript for this button or link was encountered: {faultcode:'soapenv:Client', faultstring:'HttpException: Example Error Message Class.BananaWebService.fetchBanana: line 22, column 1', }   Is there a simple way to create friendly error messages for my users when exceptions are thrown like this:  Example Error Message   Exception Class  public class HttpException extends Exception{}   Web Service Class   @RestResource(urlMapping='/BananaWebService/*') global class BananaWebService {   webservice static void fetchBanana(Id accountId) {      throw new HttpException('Example Error Message');   } }   Javascript code   {!REQUIRESCRIPT("/soap/ajax/28.0/connection.js")}  {!REQUIRESCRIPT("/soap/ajax/28.0/apex.js")}   var accountId = "{!Account.Id}"; sforce.apex.execute("BananaWebService","fetchBanana", { accountId: accountId });  window.location.reload();