Error:     java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.vinicius.chatandroid/com.example.vinicius.chatandroid.Janela}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference;   code:  public void sendMessage(View view) {     EditText ip = (EditText) findViewById(R.id.txtIp);     EditText porta = (EditText) findViewById(R.id.txtPorta);     String txtIp = ip.getText().toString();     String pota = porta.getText().toString();     int txtPorta = Integer.parseInt(pota);     Intent intent = new Intent(this, Janela.class);     intent.putExtra("ip", txtIp);     intent.putExtra("porta", txtPorta);     startActivity(intent); }   new activity   public Janela() {     Intent intent = getIntent();     String ip = intent.getStringExtra("ip");     int porta = intent.getIntExtra("porta",0);     this.conexao = new Conexao(ip, porta);     conexao.addObserver(this);     escreve("Chat iniciado com " + conexao.getIp() + ":" + conexao.getPorta()); }
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?
95979
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was:      Apex trigger updatequotestatus caused an unexpected exception, contact your administrator: updatequotestatus: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.updatequotestatus line 5, column 1.   Error Occured at Line:     if((t.what.getsobjecttype() == quote__c.sobjecttype) &amp;&amp; (t.subject.substring(0,5) == 'Email')  trigger updatequotestatus on task (after insert, after update){     Set&lt;Id&gt; quoteIds = new Set&lt;Id&gt;();     List&lt;quote__c&gt; quotes = new List&lt;quote__c&gt;();      for(task t:trigger.new){         if(t.whatId!=null){             if((t.what.getsobjecttype() == quote__c.sobjecttype) &amp;&amp; (t.subject.substring(0,5) == 'Email')){                 quoteIds.add(t.whatId);             }         }     }      for(quote__c q:[select StageName__c from quote__c where Id IN : quoteIds]){         quote__c qt = new quote__c();         qt.Id = q.Id;         qt.StageName__c = 'Proposal Sent';         quotes.add(qt);     }      if(quotes.size()&gt;0){         update quotes;     } }
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;         }           }           }
112290
This code throws a NullReferenceException when it calls ExecuteScalar:  selectedPassengerID = 0;  //SqlCommand command = GenericDataAccess.CreateCommand();   // 2nd test string connectionString = ""; SqlConnection conn;  connectionString = ConfigurationManager.     ConnectionStrings["ConnST-MHM"].ConnectionString; conn = new SqlConnection(connectionString); SqlCommand command = new SqlCommand(); command.CommandType = CommandType.StoredProcedure ; command.Connection = conn; command.CommandText = "SearchForPassenger";  SqlParameter param;  param = command.CreateParameter(); param.ParameterName = "@name"; param.Value = pName; // Session[""]; param.DbType = DbType.String; command.Parameters.Add(param);  param = command.CreateParameter(); param.ParameterName = "@flightDate"; param.Value = date;  param.DbType = DbType.String; command.Parameters.Add(param);  param = command.CreateParameter(); param.ParameterName = "@ticketNo"; param.Value = ticketNumber;  param.DbType = DbType.Int32; command.Parameters.Add(param);  int item;  command.Connection.Open(); item = (int)command.ExecuteScalar();
18034
when i try to save the following code, i got the error below. Following same instructions given in this link, but still errors. Am i doing anything wrong here? please suggest.    @isTest private class WebSvcCalloutTest {     @isTest static void testEchoString() {         Account a = new Account(name='Tester',SAP_KUNNR__c='1172');         insert a;                       // This causes a fake response to be generated         Test.setMock(WebServiceMock.class, new WebServiceMockImpl());      } }   Error:  Save error: Method does not exist or incorrect signature: Test.setMock(Type, WebServiceMockImpl)    WebSvcCalloutTest.cls         @isTest global class WebServiceMockImpl implements WebServiceMock {    global void doInvoke(            Object stub,            Object request,            Map&lt;String, Object&gt; response,            String endpoint,            String soapAction,            String requestName,            String responseNS,            String responseName,            String responseType) {          sapComDocumentSapSoapFunctionsMcS.Z_GSSMWFM_HNDL_EVNTRQST00 sap1 = new sapComDocumentSapSoapFunctionsMcS.Z_GSSMWFM_HNDL_EVNTRQST00();                Map&lt;String,String&gt; mapSAP = new Map&lt;String,String&gt; {};         sapComDocumentSapSoapFunctionsMcS.ZgssmbstDatarcrd01 req = new sapComDocumentSapSoapFunctionsMcS.ZgssmbstDatarcrd01();               sapComDocumentSapSoapFunctionsMcS.ZGssmwfmHndlEvntrqst00Response_element ret =  sap1.ZGssmwfmHndlEvntrqst00('',req);         response.put('response_x', ret);     } }
23909
Looking for reviewers to suggest optimization and improvements, and to evaluate coding practices.  final class Variables {     private final int x;     private final int y;      Variables(int x2, int y2) {         this.x = x2;         this.y = y2;     }      public int getX() {         return x;     }      public int getY() {         return y;     }      @Override public String toString()  {          return "x = " + x + " y = " + y;     } }  public final class FindMissing {      private FindMissing() {};      /**  * Takes an input a sorted array with two variables that repeat in the  * range. Remaining variable are consecutive. and returns two variables that repeats  *   * eg: for a range of 1,2,3,4, a valid input is [1, 4], [1, 3] etc.  *   * @param a : the sorted array.  */ /*  * Why is start needed ?  * If start is not given then if a1 is empty how do we know if missing numbers were  * [1, 2] or [4, 5] ??.   */ public static Variables sortedConsecutiveTwoMissing (int[] a, int startOfRange) {     if (a == null) throw new NullPointerException("a1 cannot be null. ");      int low = startOfRange;     // calculating the highest value of the range. it needs to be 2 more than length since all elememts are consecutive.     int high = startOfRange + (a.length - 1) + 2;      int i = 0;     boolean foundX = false;     int x = 0;       while (i &lt; a.length) {         if (a[i] != low) {             if (foundX) {                 return new Variables(x, low);             } else {                 x = low;                 foundX = true;             }         } else {             i++;         }         low++;     }      return new Variables(x, high);  }  public static void main(String[] args) {         // unsortedConsecutiveTwoMissing         int[] a6 = {1, 4};         System.out.println("Expected 2 and 3, Actual " + sortedConsecutiveTwoMissing(a6, 1));         // unsortedConsecutiveTwoMissing         int[] a7 = {-4, -1};         System.out.println("Expected -3 and -2, Actual " + sortedConsecutiveTwoMissing(a7, -4));         int[] a8 = {-4, -3, -2, -1};         System.out.println("Expected 0 and 1, Actual " + sortedConsecutiveTwoMissing(a8, -4));         int[] a9 = {5};         System.out.println("Expected 4 and 6, Actual " + sortedConsecutiveTwoMissing(a9, 4));         }      }
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); }
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.
103112
When and why would somebody do the following:  doSomething( (MyClass) null );   Have you ever done this? Could you please share your experience?
24554
I have a lookup relationship.  If I just do the following query it works fine:  Sobject c = [select field__r.fieldchild__c from custom_obj where Id = :someId]; system.debug('c:' + c);   However with the following I get an error:  Sobject c = [select field__r.fieldchild__c from custom_obj where Id = :someId]; String c2 = (String) r.getSobject('field__r').get('fieldchild__c');   Error message:     FATAL_ERROR System.NullPointerException: Attempt to de-reference a   null object
37422
I'm getting this error every few days. I won't see the error for a few days then I'll get a flurry of 20 or so all with in a minute or so.  I've been very thorough going throw my code so that I'm using this basic setup for my DB access.  try {   myConnection.Open();   mySqlDataAdapter.Fill(myDataTable);   myConnection.Close(); } Catch (Exception err) {   if (myConnection.State != ConnectionState.Closed) myConnection.Close();   throw err; }   The way I understand it this should execute my queries and immediately release the connection back to the pool but if something goes wrong with the query then I catch the excpetion close my connection then throw the error up, which eventually gets trapped at the application level and logs and emails me the error.  Even using this throughout my code I'm still running across the issue. What can I do to diagnose the root cause of the issue?
79268
Here is my code `  global with sharing class ReportsListController {     public String dcarr { get; set; }    public static ReportsColumnMap__c repcols { get; set; }    public ReportsListController() { } // empty constructor    @RemoteAction   global static List&lt;ReportsColumnMap__c&gt; getRepCols(String dcarr) {             List&lt;ReportsColumnMap__c&gt; repcols =          [SELECT ColumnName__c,SObject__c ,COUNT(ID) FROM ReportsColumnMap__c WHERE ColumnName__c IN ('OWNER','FIRST_NAME','LAST_NAME','TITLE','COMPANY','LEAD_SOURCE','RATING','STREET','EMAIL') AND SObject__c !='null' GROUP BY SObject__c ,ColumnName__c];     return repcols;   } }   `
107801
I posted the code below to the Sun developers forum since I thought it was erroring (the true error was before this code was even hit).  One of the responses I got said it would not work and to throw it away.  But it is actually working.  It might not be the best code (I am new to Java) but is there something inherently "wrong" with it?   =============  CODE:   private static void ImportFromCsvToAccessTable(String mdbFilePath, String accessTableName  , String csvDirPath , String csvFileName ) throws ClassNotFoundException, SQLException {      Connection msConn = getDestinationConnection(mdbFilePath);     try{          String strSQL = "SELECT * INTO " + accessTableName + " FROM [Text;HDR=YES;DATABASE=" + csvDirPath + ";].[" + csvFileName + "]";         PreparedStatement selectPrepSt = msConn.prepareStatement(strSQL );         boolean result = selectPrepSt.execute();                 System.out.println( "result = " + result );      } catch(Exception e) {         System.out.println(e);     } finally {         msConn.close();     } }
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.
119160
This Trigger is on lead (Before Insert, Before Update) and it errors (System.NullPointerException: Attempt to de-reference a null object). I'm getting this error when i'm posting "Web to Lead". However i do have the right ORG iD and Record type id included on the xml file:   &lt;input type=hidden name="oid" value="xxxxxxxxxxxxx"&gt; &lt;input type=hidden name="recordType" id="recordType" value="zzzzzzzzzzzzzzzzzz"&gt;    trigger IAAILeadTrigger on Lead (before insert, before update){ //BEGIN: S-444340 T-561808 - Process only IAA Remarketing Recordtype data     Map&lt;ID,Schema.RecordTypeInfo&gt; rt_Map = Lead.sObjectType.getDescribe().getRecordTypeInfosById();      //Looks up the branches based on the Lead PostalCode     if(trigger.isBefore){          for(Lead ld : trigger.new){                      if (rt_map.get(ld.recordTypeID).getName().containsIgnoreCase('IAA Remarketing') )                if( trigger.isInsert ||                    (trigger.isUpdate &amp;&amp; ld.Branch__c == null) ||                   (trigger.isUpdate &amp;&amp; ld.PostalCode != trigger.oldMap.get(ld.id).PostalCode)               ){                   leads.add(ld);               }           }           }                 //Only check the leads that are in the lead list and NOT the full trigger.new list         if(!leads.isEmpty()){             LeadController.GetLeadBranches(leads);           }     }  }
28359
I'm trying to build an Android test application integrated to the SalesForce platform. I have downloaded the SDK from , and imported it to my workspace. Everything works fine except my test app, even the  they have provided along with the SDK work without problem. As a first step, what I tried was to clone the basic features (just login as of now) from the RestExplorer app. The following are my important files.  public class Home extends Activity {  private PasscodeManager passcodeManager; private RestClient client; private TokenRevocationReceiver tokenRevocationReceiver;  RestClient getClient() {     return client; }  @Override protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);      passcodeManager = SalesforceSDKManager.getInstance().getPasscodeManager();     tokenRevocationReceiver = new TokenRevocationReceiver(this);     setContentView(R.layout.activity_home);  }  @Override  public void onResume() {     super.onResume();     registerReceiver(tokenRevocationReceiver, new IntentFilter(ClientManager.ACCESS_TOKEN_REVOKE_INTENT));           if (passcodeManager.onResume(this)) {   // Bring up passcode screen if needed         String accountType = SalesforceSDKManager.getInstance().getAccountType();   // Login options         new ClientManager(this, accountType, SalesforceSDKManager.getInstance().getLoginOptions(), SalesforceSDKManager.getInstance().shouldLogoutWhenTokenRevoked()).getRestClient(this, new RestClientCallback() {    // Get a rest client             @Override             public void authenticatedRestClient(RestClient client) {                 if (client == null) {                     SalesforceSDKManager.getInstance().logout(Home.this);                     return;                 }                 Home.this.client = client;                           }         });     } }  @Override protected void onPause() {     passcodeManager.onPause(this);     unregisterReceiver(tokenRevocationReceiver);     super.onPause(); } }   I have added the permissions as required  &lt;permission android:name="com.salesforce.samples.restexplorer.C2D_MESSAGE"     android:protectionLevel="signature" /&gt;  &lt;uses-permission android:name="com.salesforce.samples.restexplorer.C2D_MESSAGE" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/&gt; &lt;uses-permission android:name="android.permission.GET_ACCOUNTS"/&gt; &lt;uses-permission android:name="android.permission.MANAGE_ACCOUNTS"/&gt; &lt;uses-permission android:name="android.permission.ACCOUNT_MANAGER"/&gt;   And extended the application object to give a call to init();  public class MyApp extends Application { @Override public void onCreate() {     super.onCreate();     SalesforceSDKManager.initNative(getApplicationContext(), new KeyImpl(), Home.class); } }   Now, I'm getting the error in my Android debug log. The log as I see is attached below. It keep the activity restarting till I forcefully kill the application.  11-08 15:56:23.883: I/ClientManager:getRestClient(9334): No account of type com.salesforce.androisdk found 11-08 15:56:23.898: W/AccMgrCallback:run(9334): android.accounts.AuthenticatorException: bind failure 11-08 15:56:23.898: W/AccMgrCallback:run(9334):     at android.accounts.AccountManager.convertErrorToException(AccountManager.java:1726) 11-08 15:56:23.898: W/AccMgrCallback:run(9334):     at android.accounts.AccountManager.access$400(AccountManager.java:144) 11-08 15:56:23.898: W/AccMgrCallback:run(9334):     at android.accounts.AccountManager$AmsTask$Response.onError(AccountManager.java:1572) 11-08 15:56:23.898: W/AccMgrCallback:run(9334):     at android.accounts.IAccountManagerResponse$Stub.onTransact(IAccountManagerResponse.java:69) 11-08 15:56:23.898: W/AccMgrCallback:run(9334):     at android.os.Binder.execTransact(Binder.java:388) 11-08 15:56:23.898: W/AccMgrCallback:run(9334):     at dalvik.system.NativeStart.run(Native Method)   Do anyone have any idea about this isse? It is such a basic app, I was not expecting anything unusual. Did I do anything wrong in my app?
46641
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady); var listTitle = []; var listUrl = []; var listIsActive = []; var listOrder = [];  function sharePointReady(){ var siteUrl = mysite;     var clientContext = new SP.ClientContext(siteUrl); var oList = clientContext.get_web().get_lists().getByTitle('Privacy Statements');  var camlQuery = new SP.CamlQuery(); camlQuery.set_viewXml(''); this.collListItem = oList.getItems(camlQuery);  clientContext.load(collListItem);  clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));         }    function onQuerySucceeded(sender, args) {  var listItemEnumerator = collListItem.getEnumerator();   while (listItemEnumerator.moveNext()) {     var oListItem = listItemEnumerator.get_current();     listTitle.push(oListItem.get_item('Title'));     listUrl.push(oListItem.get_item('PrivacyStatementUrls').get_url());      listIsActive.push(oListItem.get_item('IsActive'));     listOrder.push(oListItem.get_item('SortOrder'));    } sessionStorage.setItem('Title', JSON.stringify(listTitle)); sessionStorage.setItem('Url', JSON.stringify(listUrl)); sessionStorage.setItem('IsActive', JSON.stringify(listIsActive)); sessionStorage.setItem('Order', JSON.stringify(listOrder)); var retrievedTitle = sessionStorage.getItem("Title"); var arTitle = JSON.parse(retrievedTitle); var retrievedUrl = sessionStorage.getItem("Url"); var arUrl = JSON.parse(retrievedUrl); var retrievedIsActive = sessionStorage.getItem("IsActive"); var arIsAct = JSON.parse(retrievedIsActive); var retrievedOrd = sessionStorage.getItem("Order"); var arOrd = JSON.parse(retrievedOrd);  var test = '' for(x=0; x&lt;arTitle.length+1;x++) {      for(i=0; i&lt;arTitle.length+1;i++)     {          if(arIsAct[i] == true){             if(arOrd[i] == x){                 test +='&lt;a href="'+arUrl[i]+'"&gt;'+arTitle[i]+'&lt;/a&gt;&lt;br&gt;';             }            }      } }  document.getElementById('test').innerHTML = test; }  function onQueryFailed(sender, args) {  alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace()); }   I am trying to use caching with sessionstorage when getting items from a list, so it doesn't have to keep querying the list over and over again. It can just check with the sessionstorage and if its in the list there is no need to get the item but if its not in sessionstorage get the item from the list. I am not sure how to do this, my code above shows my attempt