My idea is using a AsynTask download a dataset and store in a arrayList. That I have checked and works well. In the onPostExecute method I call a function to update my listView and I load the data stored in the ArrayList.  Code:  protected void onPostExecute(String result)  {            progressDialog.setProgress(99);     actualizarDisplay(); }   The method actulizarDisplay:  dataAdapter = new MyCustomAdapter(this,R.layout.servicio, listaServicios); ListView listView = (ListView) findViewById(R.id.listaServ); listView.setAdapter(dataAdapter);   And the class MyCustomAdapter:  private class MyCustomAdapter extends ArrayAdapter&lt;Servicio&gt;  {  private ArrayList&lt;Servicio&gt; servicioList;  public MyCustomAdapter(Context context, int textViewResourceId,ArrayList&lt;Servicio&gt; servicioList)  {     super(context, textViewResourceId,servicioList);     this.servicioList = new ArrayList&lt;Servicio&gt;();     this.servicioList.addAll(servicioList); }  private class ViewHolder  {    TextView nombre, hora, lugar, fecha;    ImageView tipo;    }  @Override public View getView(int position, View convertView, ViewGroup parent)  {     ViewHolder holder = null;      if (convertView == null)      {        LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);        convertView = vi.inflate(R.layout.servicio, null);         holder = new ViewHolder();        holder.nombre = (TextView) convertView.findViewById(R.id.titulo);        holder.lugar = (TextView) convertView.findViewById(R.id.lugar);        holder.hora = (TextView) convertView.findViewById(R.id.hora);        holder.fecha = (TextView) convertView.findViewById(R.id.fecha);        convertView.setTag(holder);     }      else       {         holder = (ViewHolder) convertView.getTag();      }       Servicio servicio = servicioList.get(position); Log.i("ConvertView", servicio.getNombre()); // the correct value is displayed      holder.nombre.setText(servicio.getNombre());      holder.hora.setText(servicio.getHora());      holder.lugar.setText(servicio.getLugar());      holder.fecha.setText(servicio.getFecha());       if (servicio.tipo == 0)            holder.tipo.setImageResource(R.drawable.cultural);       return convertView;  }      }  And this is the error in the logcat, THE LINE 423 is: holder.nombre.setText(servicio.getNombre());     FATAL EXCEPTION: main java.lang.NullPointerException at   app.serviciosprote.Inicio$MyCustomAdapter.getView(Inicio.java:423)     at android.widget.AbsListView.obtainView(AbsListView.java:2350)         at android.widget.ListView.measureHeightOfChildren(ListView.java:1409)         at android.widget.ListView.onMeasure(ListView.java:1273)         at android.view.View.measure(View.java:15286)         at android.widget.RelativeLayout.measureChild(RelativeLayout.java:602)         at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:415)       at android.view.View.measure(View.java:15286)       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4832)             at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390)             at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)             at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)             at android.view.View.measure(View.java:15286)             at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4832)             at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)               at android.view.View.measure(View.java:15286)             at android.widget.LinearLayout.measureVertical(LinearLayout.java:833)             at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)             at android.view.View.measure(View.java:15286)             at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4832)             at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)             at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2269)   Thanks for trying to help
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?
51956
For creating a list template programmatically by using server object, I'm using the SaveAsTemplate() function.  SPSecurity.RunWithElevatedPrivileges(delegate {   using (SPSite oSPsite = new SPSite(strSiteURL))   {     oSPsite.AllowUnsafeUpdates = true;     using (SPWeb oSPWeb = oSPsite.OpenWeb())     {       oSPWeb.AllowUnsafeUpdates = true;        SPList list = oSPWeb.Lists[strListName];       string bkpTemplateName = "bkp" + strListName + ".stp";       list.SaveAsTemplate(bkpTemplateName, bkpTemplateName.Replace(".stp",""), "Description", true);        list.Update();       oSPWeb.AllowUnsafeUpdates = false;     }     oSPsite.AllowUnsafeUpdates = false;   } });   But, is there a way to do the same by using CSOM?
3800
I can't get to the bottom of this error, because when the debugger is attached, it does not seem to occur.  Collection was modified; enumeration operation may not execute  Below is the code. This is a WCF server in a Windows service. The method NotifySubscribers() is called by the service whenever there is a data event (at random intervals, but not very often - about 800 times per day). When a Windows Forms client subscribes, the subscriber ID is added to the subscribers dictionary, and when the client unsubscribes, it is deleted from the dictionary. The error happens when (or after) a client unsubscribes. It appears that the next time the NotifySubscribers() method is called, the foreach() loop fails with the error in the subject line. The method writes the error into the application log as shown in the code below. When a debugger is attached and a client unsubscribes, the code executes fine. Do you see a problem with this code? Do I need to make the dictionary thread-safe? [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class SubscriptionServer : ISubscriptionServer {     private static IDictionary&lt;Guid, Subscriber&gt; subscribers;      public SubscriptionServer()     {                     subscribers = new Dictionary&lt;Guid, Subscriber&gt;();     }      public void NotifySubscribers(DataRecord sr)     {         foreach(Subscriber s in subscribers.Values)         {             try             {                 s.Callback.SignalData(sr);             }             catch (Exception e)             {                 DCS.WriteToApplicationLog(e.Message,                    System.Diagnostics.EventLogEntryType.Error);                  UnsubscribeEvent(s.ClientId);             }         }     }          public Guid SubscribeEvent(string clientDescription)     {         Subscriber subscriber = new Subscriber();         subscriber.Callback = OperationContext.Current.                 GetCallbackChannel&lt;IDCSCallback&gt;();          subscribers.Add(subscriber.ClientId, subscriber);                  return subscriber.ClientId;     }      public void UnsubscribeEvent(Guid clientId)     {         try         {             subscribers.Remove(clientId);         }         catch(Exception e)         {             System.Diagnostics.Debug.WriteLine(&quot;Unsubscribe Error &quot; +                      e.Message);         }     } }
87958
I have a page where I am trying to show which ListViews a Project is in. I can get the data I want in the Developer Console by querying ListView. However, when I try to import the following query to my code I get the following exception: "Save error: sObject type 'ListView' is not supported." Query:  SELECT Id, Name FROM ListView WHERE SObjectType = 'Project__c'   As a workaround, I am trying to instantiate an Apex:StandardSetController for Project__c and call getListViewOptions(). Notice I am not calling getListViewOptions on my ApexPages.StandardController. The relevant bit that is not working:  public MyExtension(ApexPages.StandardController notUsed) {     debugListViews(); // yields bogus results } public MyExtension(ApexPages.StandardSetController notUsed) {     debugListViews(); // yields valid results } private void debugListViews() {     ApexPages.StandardSetController controller = new ApexPages.StandardSetController([         SELECT Id FROM Project__c LIMIT 1     ]);     for (SelectOption option : controller.getListViewOptions())     {         system.debug(option);     } }   This code works perfectly in Execute Anonymous. I see a list of SelectOption each of which has a valid Name/Id combination. However, when I run this code in my extension's constructor that takes in an ApexPages.StandardController, I get only one SelectOption that is clearly bogus. The Name is "All" and the Id is "000000000000000AAA". Note: the key prefix for ListView is "00B."  To add to the mystery, this code also works as expected in my extension constructor that takes in an ApexPages.StandardSetController.  This seems like it is a Salesforce bug, but I am not allowed to submit a Development Case for this org. Has anyone run into this before and found a workaround?
57540
I'm trying to update an account list and I need to get the Ids when the update fails.  I use the getId() method but for accounts which fail I get null.  It's an update so my account already has an Id.  Is it normal ? If it is, how can I get the Ids list of non-updated accounts ?  Here is my code :  List&lt;Account&gt; accountsList = [select Id from Account];  for(Account a : accountsList) {     a.Name = 'Test', }  List&lt;Database.SaveResult&gt; res = Database.update(accountsList, false);  for (Database.SaveResult s : res) {     if (!s.isSuccess()) {         system.debug(s.getId()); // I get null here      }  }
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?
104149
When an exception is thrown in an Asp.Net web page, an error message is displayed with the complete stack trace.    Example below:       Stack Trace:     IndexOutOfRangeException: Index was outside the bounds of the array.    MyNameSpace.SPAPP.ViewDetailsCodeBehind.LoadView()  +5112   MyNameSpace.SPAPP.ViewDetailsCodeBehind.Page_Load(Object sender, EventArgs e) +67   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +13   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +43   System.Web.UI.Control.OnLoad(EventArgs e) +98   ... ...   The problem is that the Line number displayed does not correspond to the line in my code that originated the exception. In the example above, the stack shows line number 5111, yet my code behind .cs file only has 250 lines!  The aspx page is stored in a SharePoint site and the Assembly with the code behind has been deployed to GAC. Also, I've compiled in Debug mode. Given the settings above, how can I find out what line in my code caused the Exception?    Clarification as pointed out by :     In Release mode the number in front of the exception is NOT the line of code. Instead it's an offset to the native compiled code, which doesn't have any meaning to humans. More about this here:       In debug mode the PDB file will automatically map the native code offset to your .cs line in code and the number displayed WILL be the corresponding line in code.
108487
I have the code below (I've included what I believe are all relevant sections):  private String readCommand = "SELECT LEVEL FROM USERS WHERE VAL_1 = ? AND VAL_@ = ?;"; public bool read(string id) {     level = -1;     MySqlCommand m = new MySqlCommand(readCommand);     m.Parameters.Add(new MySqlParameter("", val1));     m.Parameters.Add(new MySqlParameter("", val2));     MySqlDataReader r = m.ExecuteReader();     if (r.HasRows)         level = Convert.ToInt32(r.GetValue(0).ToString());     r.Close();     return true; }   When I run this, I get an IndexOutOfBoundsException on adding the first parameter. What have I done wrong?
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?
109408
What is the best way to refresh a DataGridView when you update an underlying data source?  I'm updating the datasource frequently and wanted to display the outcome to the user as it happens.  I've got something like this (and it works), but setting the DataGridView.DataSource to null doesn't seem like the right way.  List&lt;ItemState&gt; itemStates = new List&lt;ItemState&gt;(); dataGridView1.DataSource = itemStates;  for (int i = 0; i &lt; 10; i++) {      itemStates.Add(new ItemState { Id = i.ToString() });     dataGridView1.DataSource = null;     dataGridView1.DataSource = itemStates;     System.Threading.Thread.Sleep(500); }
94863
Any Answers Will Help me to Forward and Gain Knowledge in SharePoint Development  While i am Trying to get the list Items Using Rest API Calls in SharePoint Hosted App Using Below Function  function loadingSamples()  {     var JobListName = "RRR Jobs #";     var executor;     // Initialize the RequestExecutor with the app web URL.     executor = new SP.RequestExecutor("/");      //Fetching the choice values from the Job Status Field, to show in the Dropdown field     executor.executeAsync     ({         url: "/_api/web/lists/getbytitle('" + encodeURIComponent(JobListName) + "')/fields/getbytitle('Job Status')?$select=Choices",         method: "GET",         headers: { "Accept": "application/json; odata=verbose" },         success: successHandlerStatus,         error: errorHandler     }); } function successHandlerStatus(data)  {     alert("sucesss") }  function errorHandler(data, errorCode, errorMessage)  {     alert("errorMessage") }   It's always going to error function named errorHandler With  Error Code as -1002 and Error Message as Bad Request and Inside Data -> Body , the Error message is  {     "error":{            "code":"-1,Microsoft.SharePoint.Client.InvalidClientQueryException",         "message":{             "lang":"en-US",             "value":"The expression \"web/lists/getbytitle('DWR Jobs \" is not valid."         }     } }   Note :    This is working code in Sharepoint Hosted App that previously hosted in another Windows server. Now i hosted this App in New windows server,it's successfully hosted but it gives above mentioned Error in Rest Service Call.
85931
I want to open an Excel file through an Apex dialog box, then browse the information in my file line and display it with visualforce. I show you my code  public class ImportExcel {       public String fileName{get; set;}     public Blob contentFile{get;set;}     public String[] csvFileLines{get;set;}     public List&lt;String&gt; acclist{get;set;}     public String[] data{get;set;}     public ImportExcel(){         csvFileLines = new String[]{};         acclist = New List&lt;String&gt;();      } public void readFile(){         try         {             fileName=contentFile.toString();         }catch(Exception e){         ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'Please upload a valid CSV document');         ApexPages.addMessage(myMsg);              return ;          }         csvFileLines=fileName.split('\n');          system.debug(csvFileLines);         for(Integer i=0;i&lt;csvFileLines.size();i++){             data=csvFileLines[i].split(',');             acclist.add(data[i]);         }     } }   Once I execute my code, it puts me this error:     13:52:13:012 VARIABLE_ASSIGNMENT   [15]|e|"common.apex.runtime.impl.ExecutionException: BLOB is not a   valid UTF-8 string"|0x4e4728
26736
Is there any way of doing something like,  &lt;script runat=server&gt;     Platform.Load("core","1");     //initialize DE     var _Sent = DataExtension.Init("_Sent");     //retrieve data     var _Sent_data = _Sent.Rows.Retrieve();     Write("Length: " + _Sent_data.length); //returns 0 &lt;/script&gt;   What would the external key for a system dataview be?
67438
I am using a ListView to display some images and captions associated with those images. I am getting the images from the Internet. Is there a way to lazy load images so while the text displays, the UI is not blocked and images are displayed as they are downloaded?   The total number of images is not fixed.
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;   } }   `
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
52560
I am getting "Error System.QueryException: List has no rows for assignment to SObject".   Line 1: Account ac = [select id from Account where name='testaccount' limit 1] Line 2: if(ac != null) {           //do something         }   I got the above error in line 2 if there is no record.   Any help?