I am trying to add same values on listView by user clicks, when user clicks a button, the system graps the value of two EditTexts and add it into the list.  But when I click a button Error displays:     01-14 12:46:31.623 21297-21297/com.example.transportor   E/AndroidRuntime: FATAL EXCEPTION: main       Process: com.example.transportor, PID: 21297       java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object   android.content.Context.getSystemService(java.lang.String)' on a null   object reference           at android.widget.ArrayAdapter.init(ArrayAdapter.java:310)           at android.widget.ArrayAdapter.(ArrayAdapter.java:153)           at com.example.transportor.product_list_adapter.(product_list_adapter.java:24)           at com.example.transportor.ui.home.HomeFragment$1.onClick(HomeFragment.java:59)           at android.view.View.performClick(View.java:4757)           at android.view.View$PerformClick.run(View.java:19757)           at android.os.Handler.handleCallback(Handler.java:739)           at android.os.Handler.dispatchMessage(Handler.java:95)           at android.os.Looper.loop(Looper.java:135)           at android.app.ActivityThread.main(ActivityThread.java:5235)           at java.lang.reflect.Method.invoke(Native Method)           at java.lang.reflect.Method.invoke(Method.java:372)           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)   My Homefragment:   Context mcontext;  Button addListe = (Button)root.findViewById(R.id.addL);         final ListView productListe = (ListView)root.findViewById(R.id.productList);         addListe.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 product_list PL = new product_list(quantity.getText().toString(),produit.getText().toString());                 ArrayList&lt;product_list&gt; PLL = new ArrayList&lt;&gt;();                  PLL.add(PL);                 product_list_adapter p_l_a = new product_list_adapter(mcontext,R.layout.adapter_product_list,PLL);                 productListe.setAdapter(p_l_a);             }         });   and My Product list:    private String quantity;     private String product;      public product_list(String quantity, String product) {         this.quantity = quantity;         this.product = product;     }      public String getQuantity() {         return quantity;     }      public void setQuantity(String quantity) {         this.quantity = quantity;     }      public String getProduct() {         return product;     }      public void setProduct(String product) {         this.product = product;     }   and product_list_adapter:   private Context mContext;     int mRessource;     public product_list_adapter(@NonNull Context context, int resource, @NonNull ArrayList&lt;product_list&gt; objects) {         super(context, resource, objects);         this.mContext = mContext;         mRessource = resource;     }        @NonNull     @Override     public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {         //get infos         String quatity = getItem(position).getQuantity();         String product = getItem(position).getProduct();         product_list PL = new product_list(quatity,product);         LayoutInflater iniat = LayoutInflater.from(mContext);         convertView = iniat.inflate(mRessource,parent,false);         TextView Tquantity = (TextView)convertView.findViewById(R.id.TextView1);         TextView Tproduct = (TextView)convertView.findViewById(R.id.TextView2);         Tquantity.setText(quatity);         Tproduct.setText(product);         return convertView;      }
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?
86219
I have a pageBlockTable that loops through a list of objects.  I'm trying add an onRowClick event so I can use the clicked row as data for a javascript function. However when saving in the developer console, I'm getting the error :-     (Unknown property 'ContactStandardController.c')   What am I doing wrong, why is it looking at the controller and not the pageBlockTable var?  &lt;apex:page standardController="Contact" &gt;     &lt;apex:pageBlock&gt;         &lt;apex:pageBlockTable value="{!Contact}" var="c" onRowClick="alert('{!c.Name}');"&gt;         &lt;/apex:pageBlockTable&gt;     &lt;/apex:pageBlock&gt; &lt;/apex:page&gt;
96988
I'm trying to write an Android app that requires users to select a value from a list of potentially hundreds. They're likely to know the item they're selecting to asking them to filter by typing seems like a sensible approach.  I've searched high and low but I can't find a standard way of doing this.  A spinner is no good and it takes too long to go through the list of values  An autocomplete box is no good as I need users to be contrained to only selecting items from my list.
115907
I am trying to addError on the opportunities based on one condition. But getting System.FinalException: SObject row does not allow errors error while saving the record. Below I have given the code snippet. Please let me know how I can resolve the issue.  if(Trigger.isUpdate &amp;&amp; Trigger.isBefore){         map&lt;Id,Opportunity&gt; newOpptyMap = (map&lt;Id,Opportunity&gt;)trigger.newMap;         OpportunityTriggerHelper.checkforStageDuration(newOpptyMap,Trigger.OldMap);     }   The function is below where I am adding the error statement  public static void checkforStageDuration(Map&lt;Id,Opportunity&gt; oldMap, Map&lt;Id,Opportunity&gt; newMap){         Map&lt;Id,Opportunity&gt; recordsToCheck = new Map&lt;Id,Opportunity&gt;();         for(Id oppId : newMap.keyset()){             if(newMap.get(oppId).StageName != oldMap.get(oppId).StageName){                 recordsToCheck.put(oppId,newMap.get(oppId));             }         }         List&lt;Opportunity_Stage_History__c&gt; oppStageHistory = [select Id,Expected_Stage_Duration__c,Opportunity__c,Duration__c,Reason_For_Delay__c from Opportunity_Stage_History__c where Opportunity__c IN :recordsToCheck.keyset()];         for(Opportunity_Stage_History__c oppHistory : oppStageHistory){             if(oppHistory.Duration__c&gt;oppHistory.Expected_Stage_Duration__c &amp;&amp; oppHistory.Reason_For_Delay__c==null){                 newMap.get(oppHistory.Opportunity__c).addError('The Opportunity has crossed it\'s Stage Duration, Please fill the Reason for Delay !!');             }         }     }
52986
I am trying to add map of map values, I have to intialize the map key first and then try to add value later. Below is the exact logic i am trying to achieve.  Map&lt;string,Map&lt;string,List&lt;string&gt;&gt;&gt; finalMap = new Map&lt;string,Map&lt;string,List&lt;string&gt;&gt;&gt;();  Map&lt;string,List&lt;string&gt;&gt; subMap = new Map&lt;string,List&lt;string&gt;&gt;(); submap.put('One',new list&lt;string&gt;{'One','TWO'});  finalMap.put('SUB1',new Map&lt;string,List&lt;string&gt;&gt;());  //Do some logics and finally try to add the values with the key  finalmap.get('SUB1').put(subMap); //Error as stated below  System.debug(finalmap);      ERROR :Method does not exist or incorrect signature:   [Map&lt;String,List&lt;String&gt;&gt;].put(Map&lt;String,List&lt;String&gt;&gt;)
41675
When interacting with different elements and applying multiple actions it  may be quite convenient in some situations if we could do:  WebElement myInput = driver.findElement(By.id("my-input-id")); myInput.clear().sendKeys("test");   Instead of:  WebElement myInput = driver.findElement(By.id("my-input-id")); myInput.clear() myInput.sendKeys("test");   But, the problem is , sendKeys() and other "action" methods cannot be chained as is - they return void and not the current WebElement.  What would be the easiest way to achieve chaining multiple actions?
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)
3278
So, I understand that the following doesn't work, but why doesn't it work?  interface Adapter&lt;E&gt; {}  class Adaptulator&lt;I&gt; {     &lt;E, A extends I &amp; Adapter&lt;E&gt;&gt; void add(Class&lt;E&gt; extl, Class&lt;A&gt; intl) {         addAdapterFactory(new AdapterFactory&lt;E, A&gt;(extl, intl));     } }   The add() method gives me a compile error, "Cannot specify any additional bound Adapter&lt;E&gt; when first bound is a type parameter" (in Eclipse), or "Type parameter cannot be followed by other bounds" (in IDEA), take your pick.  Clearly you're just Not Allowed to use the type parameter I there, before the &amp;, and that's that. (And before you ask, it doesn't work if you switch 'em, because there's no guarantee that I isn't a concrete class.) But why not? I've looked through Angelika Langer's FAQ and can't find an answer.  Generally when some generics limitation seems arbitrary, it's because you've created a situation where the type system can't actually enforce correctness. But I don't see what case would break what I'm trying to do here. I'd say maybe it has something to do with method dispatch after type erasure, but there's only one add() method, so it's not like there's any ambiguity...  Can someone demonstrate the problem for me?
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;         }           }           }
4667
Getting error with this code but I can't figure it out  trigger LeadConvert on Lead (after insert) {     list leadsToConvert = new list();      Database.LeadConvert lc;     string convertedStatus = '';     list convertStatusList = new list();     convertStatusList = [Select Id, MasterLabel                          from LeadStatus where IsConverted=true limit 1];     if(convertStatusList.size() &gt; 0){         convertedStatus = convertStatusList[0].MasterLabel;         }     else{              convertedStatus = 'Closed - Converted';          }      for(Lead l : trigger.New){         if(l.AutoConvert__c == true){             lc = new database.LeadConvert();             lc.setLeadId(l.ID);             lc.setDoNotCreateOpportunity(true);              lc.setConvertedStatus(convertedStatus);             leadsToConvert.add(lc);         }     }      list lcrList = new list();     lcrList = Database.convertLead(leadsToConvert); }
116653
I have this:  If String.IsNullOrEmpty(editTransactionRow.pay_id.ToString()) = False Then     stTransactionPaymentID = editTransactionRow.pay_id 'Check for null value End If   Now, when editTransactionRow.pay_id is Null Visual Basic throws an exception. Is there something wrong with this code?
69888
I have a custom object, with a Text Name (ID) field. When I upsert two records with identical Name/ID, but otherwise different values, in two separate upsert statement, one record results, as expected.  When I create a list, add these records to the list, and then upsert the list, I get a DUPLICATE_VALUE error. What gives? By definition, upsert should not do this, should it? Even worse: it doesn't matter whether a record with the identical Name already exists or not, the upsert will fail in both scenarios.  By the way: by default upsert a does not use the Name/ID field as identifying/unique field, as you might expect. You need to do upsert a Name  Complete code:  List&lt;Flight__c&gt; flights = new List&lt;Flight__c&gt;(); Flight__c f1 = new Flight__c(); f1.Name = 'ABC123'; f1.Flight_Number__c = 'ABC'; flights.add(f1);  Flight__c f2 = new Flight__c(); f2.Name = 'ABC123'; f2.Flight_Number__c = '123'; flights.add(f2);  upsert flights Name;      Error message: Line: 12, Column: 1 System.DmlException: Upsert failed.   First exception on row 0; first error: DUPLICATE_VALUE, Duplicate   external id specified: ABC123: [Name]   Name being the standard identifying field of a custom object. You cannot edit the properties of this field, e.g. making it unique or not unique.
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))
122089
I try to add an item to my sharepoint list from a custom web part. Is there any mistake in my code?  [WebMethod]         public static string AjouterDemande()         {             SPList ListeDemandeConge = SPContext.Current.Site.RootWeb.Lists["DEMANDE CONGÉ"];             SPListItem ListItem = ListeDemandeConge.Items.Add();             ListItem["CODE"] = code;             ListItem["DEMANDEUR"] = Utilisateur.LoginName;             ListItem["DATE DEMANDE"] = DateTime.Today.Date;             ListItem["DATE FIN"] = EndDateD;             ListItem["DATE DEPART"] = StartDateD;             ListItem["DUREE"] = int.Parse(DayCount);             ListItem["PREMIER RESPONSABLE"] = Employe.FirstSuperior.LoginName;             ListItem["DEUXIEME RESPONSABLE"] = Employe.SecondSuperior.LoginName;             ListItem["PRESENCE PRES"] = Boolean.Parse(FirstRespPresent);             ListItem["SOLDE CONGE"] = Conge.SoldeAnneeConge;             ListItem["MOIS"] = int.Parse(StartDateTab[1]);             ListItem["ANNEE"] = int.Parse(StartDateTab[0]);             ListItem["JOURS APPROUVEES"] = 0;             ListItem.Update();             ListeDemandeConge.Update();             return "true";          }   When I use F10 to process debugging step by step and get to my listitem.update(), it went out without giving any error.
11494
App version 1.0.27  If you the notification pane and click on the loading icon while it's spinning, the app will cause the app to crash.  03-26 22:51:08.331 E/AndroidRuntime(5927): FATAL EXCEPTION: main 03-26 22:51:08.331 E/AndroidRuntime(5927): java.lang.ArrayIndexOutOfBoundsException: length=0; index=-1 03-26 22:51:08.331 E/AndroidRuntime(5927): at java.util.ArrayList.get(ArrayList.java:310) 03-26 22:51:08.331 E/AndroidRuntime(5927): at com.stackexchange.marvin.ui.BaseActivity$3.onItemClick(BaseActivity.java:266) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.widget.AdapterView.performItemClick(AdapterView.java:298) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.widget.AbsListView.performItemClick(AbsListView.java:1100) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2788) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.widget.AbsListView$1.run(AbsListView.java:3463) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.os.Handler.handleCallback(Handler.java:730) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.os.Handler.dispatchMessage(Handler.java:92) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.os.Looper.loop(Looper.java:137) 03-26 22:51:08.331 E/AndroidRuntime(5927): at android.app.ActivityThread.main(ActivityThread.java:5103) 03-26 22:51:08.331 E/AndroidRuntime(5927): at java.lang.reflect.Method.invokeNative(Native Method) 03-26 22:51:08.331 E/AndroidRuntime(5927): at java.lang.reflect.Method.invoke(Method.java:525) 03-26 22:51:08.331 E/AndroidRuntime(5927): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 03-26 22:51:08.331 E/AndroidRuntime(5927): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 03-26 22:51:08.331 E/AndroidRuntime(5927): at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:126) 03-26 22:51:08.331 E/AndroidRuntime(5927): at dalvik.system.NativeStart.main(Native Method)   (Think I should calm down on finding bugs for a little while? :P)
68403
I have this controller but I am getting this error      System.QueryException: List has no rows for assignment to SObject   public class MyController {     private final Account account;      public MyController() {         account = [SELECT Id, Name, Site FROM Account                     WHERE Id = :ApexPages.currentPage().getParameters().get('id')];             }      public Account getAccount() {         return account;     }      public PageReference save() {         update account;         return null;     } }
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?