I hope you can help me. I get an NullPointerExeption when I want to Put the NodeList / Node to my Map:  Map &lt;String, NodeList&gt; config = null;   public void loadConfiguration() {     helper helper = new helper();     NodeList nodes = null;     nodes = helper.getXPathFromFile("/root/*", "conf/config.xml");      if (nodes.getLength() &gt; 0) {         for (int i = 0; i &lt; nodes.getLength(); i++) {             String NodeName = nodes.item(i).getNodeName();             NodeList NodeItem = (NodeList) nodes.item(i);             System.out.println(NodeName); // Here the right Name puts out             System.out.println(helper.nodelistToString(NodeItem)); // here right inside XML-Code put out             config.put(NodeName, NodeItem); // Here comes the NullPointerEx.         }     } }
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?
51434
I have a std::map like this:  map&lt;wstring,int&gt; Scores;   It stores names of players and scores. When someone gets a score I would simply do:  Scores[wstrPlayerName]++;   When there is no element in the map with the key wstrPlayerName it will create one, but does it initialize to zero or null before the increment or is it left undefined?  Should I test if the element exists every time before increment?  I just wondered because I thought primitive-type things are always undefined when created.  If I write something like:  int i; i++;   The compiler warns me that i is undefined and when I run the program it is usually not zero.
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;         }           }           }
122018
I am trying to add a list into an another nested list before adding values of a list to nested list it is getting the correct value but after adding i am getting (already output) in debug log when i checked.    public List&lt;String&gt; fieldName {get;set;}  public List&lt;List&lt;String&gt;&gt; fileValuesXML; // To get the field values of xml  for(Dom.XMLNode child : SalesforceObjecet.getChildElements()) {                        objecetName = child.getText();             system.debug('Object Name in XML field  ' + objecetName );              for(Dom.XMLNode subchild : child.getChildElements())              {                 system.debug('Sub child ' + subchild.getText() );                 for(Dom.XMLNode subchildfield : subchild.getChildElements())                 {                     system.debug('Sub child Field ' + subchildfield );                     fName  = subchildfield.getText();                     fieldName.add(fName);                     //fileValuesXML.add(fieldName);                     //system.debug('Filed Name in XML field  ' + fieldName);                 }                  system.debug('Filed Name before affing to filevalueXML  ' + fieldName);                                     fileValuesXML.add(fieldName);                 fieldName.clear();                 system.debug('Filed Name after affing to filevalueXML  ' + fileValuesXML);             }    }    I am getting values in debug log as:     Filed Name before affing to filevalueXML  (AccountSource, field3)   Filed Name after affing to filevalueXML  ((), (already output),   (already output))
3140
The following code should find the appropriate project tag and remove it from the XmlDocument, however when I test it, it says:  The node to be removed is not a child of this node.  Does anyone know the proper way to do this?  public void DeleteProject (string projectName) {     string ccConfigPath = ConfigurationManager.AppSettings["ConfigPath"];      XmlDocument configDoc = new XmlDocument();      configDoc.Load(ccConfigPath);      XmlNodeList projectNodes = configDoc.GetElementsByTagName("project");      for (int i = 0; i &lt; projectNodes.Count; i++)     {         if (projectNodes[i].Attributes["name"] != null)         {             if (projectName == projectNodes[i].Attributes["name"].InnerText)             {                                                                 configDoc.RemoveChild(projectNodes[i]);                 configDoc.Save(ccConfigPath);             }         }     } }   UPDATE  Fixed. I did two things:  XmlNode project = configDoc.SelectSingleNode("//project[@name='" + projectName + "']");   Replaced the For loop with an XPath query, which wasn't for fixing it, just because it was a better approach.  The actual fix was:  project.ParentNode.RemoveChild(project);   Thanks Pat and Chuck for this suggestion.
16290
This is a canonical question and answer developed by the community to help address common questions. If you've been directed here, or your question has been closed as a duplicate, please look through the resources here and use them to shape more specific questions. To browse all canonical questions and answers, navigate to the  tag. This question and answer is owned by the community! If you can improve it and make it more useful, you're welcome to edit it. I am building a trigger, a unit test, or other Apex code. I'm working with sObject records, and trying to access related record information. For example, I might have a structure like this: Account a = new Account(Name = 'Test'); insert a;  Opportunity o = new Opportunity(Name = 'Donation', AccountId = a.Id); insert o;  System.assertEquals(o.Account.Name, 'Test', 'Correct Account associated'); // Assertion fails!  Or, in a trigger, I might be aiming for something like this: trigger ContactTrigger on Contact (after insert) {     for (Contact c : Trigger.new) {         if (c.Account.Name == 'Test') {             // Take some action here         }      } }  Why doesn't this work? Why am I getting null values, or NullPointerExceptions?
108596
I have a custom object that I want to set a unique key based on on lookup values. When I tried to create a workflow update I was blowing past the size limit so I developed it into a trigger and it seems to be working as intended.   I thought since I am already developing a field update trigger, I might as well add on a default name method so everything is contained into one file as opposed to having workflow and triggers updating the record.   When I introduced this method it returns "null null".   public static void setRecordName(List&lt;Responsible_Party__c&gt; newList) {     for(Responsible_Party__c r : newList)     {         r.Name = r.Practice__r.Name + ' ' + r.User__r.Name;     } }   Where practice is a lookup to another custom object and user is a lookup to the user object.   If I change the values to just use the field:  public static void setRecordName(List&lt;Responsible_Party__c&gt; newList) {     for(Responsible_Party__c r : newList)     {         r.Name = r.Practice__c + ' ' + r.User__c;     } }   I get "a1Gg00000049v9xEAA 005A0000006ykwnIAA". How can I get the names to display and not null?
113702
I need to easily serialize (save as long text field in database) and deserialize (convert back to a class) a parameter list in Apex of String -> Object value pairs.  My first idea was just to write a class like this...:  public class Parameters{     private Map&lt;String, Object&gt; parameters = new Map&lt;String, Object&gt;();      public void add(String name, Object value) {         this.parameters.put(name, value);     }      public Object get(String name) {         Object result = null;          if(this.parameters.containsKey(name)) {             result = this.parameters.get(name);         }         return result;     }     }    ... and use JSON.serialize and deserialize..  Parameters params = new Parameters(); params.add('Name', 'Robert'); params.add('Age', 36); String serialized = JSON.serialize(params); Parameters deserialized = (Parameters) JSON.deserializeStrict(serialized, Parameters.class); System.assertEquals(params, deserialized);   but then I got this error message:     System.JSONException: Apex Type unsupported in JSON: Object   Any idea or experience on how to implement such a Parameter class that is able to at least hold all basic (non-collection) types?!
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
37684
I'm trying create a Map using a name field as key.  Sample code:  Set&lt;String&gt; priceBooksNames = new Set&lt;String&gt;(); priceBooksNames.add('LN-200'); priceBooksNames.add('LN-100');  Map&lt;string,PriceBook2&gt; priceBooks = new Map&lt;string,PriceBook2&gt;([SELECT name,id FROM PriceBook2 WHERE name=:priceBooksNames ]); system.debug(priceBooks.get('LN-100')); //this is returning NULL   I can see on console that setId on map is not getting the name field value.  VARIABLE_ASSIGNMENT [5]|priceBooks|{"serId":1,"value":{"01sb0000000hiqQAAQ":{"serId":2,"value":{"Name":"LN-100 ADULTOS","Id":"01sb0000000hiqQAAQ"}},"01sb0000000hiqGAAQ":{"serId":3,"value":{"Name":"LN-200 EMPRESAS","Id":"01sb0000000hiqGAAQ"}}}}   What I'm going wrong?
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
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();
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?
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.
42604
here is my code in which i am trying to get the product name from opportunity line item but its returning back NULL value. can anyone please help me to get that product name. I can get id from product2 but i want the name of product so that i can abbreviate it and can store it in Order_Name__c field of orderItem. After adding the product only i am firing this trigger.     public class Procuct_Adding_To_Order{  public static void productOrder(List&lt;OpportunityLineItem&gt; oli){     system.debug('-----------------------');      set&lt;id&gt; prodset = new set&lt;Id&gt;(); for(OpportunityLineItem item : oli) {   prodSet.add(item.product2id); } // collect products Map&lt;Id, product2&gt; prodMap = new Map&lt;Id, Product2&gt;([select name from product2 where id in :prodSet]);   // create a map for OLIid &amp; corresponding Product Name Map&lt;Id, string&gt; OLIprodMap = new Map&lt;Id, string&gt;();  for(OpportunityLineItem item : oli) {  OLIprodMap.put(item.id, OLIprodMap.get(oli.product2id).name); //getting Error in this line. }      set&lt;Id&gt; setOppId = new set&lt;Id&gt;();      for(OpportunityLineItem obj: oli){          setOppId.add(obj.OpportunityId);      }      list&lt;opportunity&gt; needed = [Select Master_Opportunity__c from opportunity Where Opportunity.id =: setOppId];         List&lt;OrderItem&gt; orderIt = new List&lt;OrderItem&gt;();     for(Order ord: [Select id from Order where opportunityId =: needed[0].Master_Opportunity__c])       {        for(OpportunityLineItem o : oli)        {           OrderItem op = new OrderItem();          op.Opportunity_del__c = needed[0].Master_Opportunity__c;          op.orderId = ord.id;         op.Order_Name__c = o.product2Id;         system.debug('-----------------------3333333333333333333333'+ o.Product2Id);         op.PriceBookEntryId = o.PriceBookEntryId;         op.Quantity = o.Quantity;         op.UnitPrice = 100;         orderIt.add(op);            }          }     upsert orderIt;  } }
16676
Eclipse is giving me a warning of the following form:     Type safety: Unchecked cast from Object to HashMap   This is from a call to an API that I have no control over which returns Object:  HashMap&lt;String, String&gt; getItems(javax.servlet.http.HttpSession session) {   HashMap&lt;String, String&gt; theHash = (HashMap&lt;String, String&gt;)session.getAttribute("attributeKey");   return theHash; }   I'd like to avoid Eclipse warnings, if possible, since theoretically they indicate at least a potential code problem.  I haven't found a good way to eliminate this one yet, though.  I can extract the single line involved out to a method by itself and add @SuppressWarnings("unchecked") to that method, thus limiting the impact of having a block of code where I ignore warnings.  Any better options?  I don't want to turn these warnings off in Eclipse.  Before I came to the code, it was simpler, but still provoked warnings:  HashMap getItems(javax.servlet.http.HttpSession session) {   HashMap theHash = (HashMap)session.getAttribute("attributeKey");   return theHash; }   Problem was elsewhere when you tried to use the hash you'd get warnings:  HashMap items = getItems(session); items.put("this", "that");  Type safety: The method put(Object, Object) belongs to the raw type HashMap.  References to generic type HashMap&lt;K,V&gt; should be parameterized.
57401
I have been working on a Java project for a class for a while now. It is an implementation of a linked list (here called AddressList, containing simple nodes called ListNode). The catch is that everything would have to be done with recursive algorithms. I was able to do everything fine sans one method: public AddressList reverse()      ListNode:    public class ListNode{   public String data;   public ListNode next; }   Right now my reverse function just calls a helper function that takes an argument to allow recursion.  public AddressList reverse(){   return new AddressList(this.reverse(this.head)); }   With my helper function having the signature of private ListNode reverse(ListNode current).  At the moment, I have it working iteratively using a stack, but this is not what the specification requires. I had found an algorithm in C that recursively reversed and converted it to Java code by hand, and it worked, but I had no understanding of it.  Edit: Nevermind, I figured it out in the meantime.  private AddressList reverse(ListNode current, AddressList reversedList){   if(current == null)        return reversedList;   reversedList.addToFront(current.getData());   return this.reverse(current.getNext(), reversedList); }   While I'm here, does anyone see any problems with this route?