I have an activity in which i am trying to get the list of data based on some condition . This selectsome() function is in the SQLiteOpenHelper subclass.  MyDBHandler dbhelper = new MyDBHandler(this); Cursor cursor; cursor = dbhelper.selectSome(value);   In class MyDBHelper.java       public Cursor selectSome(String arg)  {      String columns[]=new String[]{"_id","_hotelname","_city","_imageSrc","_rent","_address"};     String selarg[]={arg};     Cursor c=db.query(TABLE_NAME,columns,"city = ?",selarg, null,null,null);    return c; }   I am getting this error please help.  09-01 18:08:00.394 E/AndroidRuntime( 6246): FATAL EXCEPTION: main  09-01 18:08:00.394 E/AndroidRuntime( 6246): Process: com.example.hari.testapp, PID: 6246  09-01 18:08:00.394 E/AndroidRuntime( 6246): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.hari.testapp/com.example.hari.testapp.HotelList}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor android.database.sqlite.SQLiteDatabase.query(java.lang.String, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String, java.lang.String, java.lang.String)' on a null object reference  09-01 18:08:00.394 E/AndroidRuntime( 6246):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)  09-01 18:08:00.394 E/AndroidRuntime( 6246):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)  09-01 18:08:00.394 E/AndroidRuntime( 6246):     at android.app.ActivityThread.access$800(ActivityThread.java:151)  09-01 18:08:00.394 E/AndroidRuntime( 6246):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)  09-01 18:08:00.394 E/AndroidRuntime( 6246):     at android.os.Handler.dispatchMessage(Handler.java:102)  09-01 18:08:00.394 E/AndroidRuntime( 6246):     at android.os.Looper.loop(Looper.java:135)  09-01 18:08:00.394 E/AndroidRuntime( 6246):     at android.app.ActivityThread.main(ActivityThread.java:5257)  09-01 18:08:00.394 E/AndroidRuntime( 6246):     at java.lang.reflect.Method.invoke(Native Method)  09-01 18:08:00.394 E/AndroidRuntime( 6246):     at java.lang.reflect.Method.invoke(Method.java:372)  09-01 18:08:00.394 E/AndroidRuntime( 6246):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)  09-01 18:08:00.394 E/AndroidRuntime( 6246):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)  09-01 18:08:00.394 E/AndroidRuntime( 6246): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor android.database.sqlite.SQLiteDatabase.query(java.lang.String, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String, java.lang.String, java.lang.String)' on a null object reference  09-01 18:08:00.394 E/AndroidRuntime( 6246):     at com.example.hari.testapp.databaseFiles.MyDBHandler.selectSome(MyDBHandler.java:113)
129
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?  What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
20439
I am trying to get this trigger to work but it is giving me an error and I am not able to figure out why. The error I am getting is "attempt to de-reference a null object)  Why trigger? We have a Destinations object which is linked to Supplier products object via a lookup relationship. There are two types of supplier products(marketplace and curated) We want to count the number of live Supplier products and put them in a separate fields(live counts for each type).  I have gotten so far to actually count the number of live products and it is giving me an error. Can any one help? I am posting the code below  Trigger code :   trigger NoOfLiveProducts on Supplier_Product__c (after insert, after Delete, after update, after undelete) {       set&lt;string&gt; destinationids = new set&lt;string&gt;();      if(trigger.isInsert) {         for(Supplier_product__c products : Trigger.new) {             destinationids.add(products.Destination__c);         }     } else if(trigger.isDelete) {         for(Supplier_product__c products : Trigger.old) {             destinationids.add(products.Destination__c);         }     }else if(trigger.isUnDelete) {         for(Supplier_product__c products : Trigger.new){             destinationids.add(products.Destination__c);         }      } else if(trigger.isUpdate) {         for(Supplier_product__c products : Trigger.new) {             destinationids.add(products.Destination__c);         }     }      if(destinationids.size() &gt; 0){         Productcounter pc = new Productcounter();         pc.updateproductCount(destinationids);     }    }   Class code :  public class Productcounter {      public void updateproductcount(set&lt;string&gt; productIDs) {           if(productIDs == null){                return;         }          if(productIDs.size() == 0){             return;         }           list&lt;Supplier_Product__c&gt; ProductList = new list&lt;Supplier_Product__c&gt;();         ProductList = [Select ID,Destination__c                     From Supplier_Product__c                     Where Destination__c = :productIDs];          integer totalCount;         map&lt;string, integer&gt; DestinationIDToProductCountMap = new map&lt;string, integer&gt;();                for(Supplier_product__c ProductItem : ProductList){             if(DestinationIDToProductCountMap.containsKey(ProductItem.Destination__c)){                 totalCount = DestinationIDToProductCountMap.get(ProductItem.Destination__c);             }else{                 totalCount = 0;             }             totalCount += 1;             DestinationIDToProductCountMap.put(ProductItem.Destination__c, totalCount);         }          list&lt;Destination__c&gt; DestinationUpdateList = new list&lt;Destination__c&gt;();         Destination__c DestinationTemp;         for(string ProductID : DestinationIDToProductCountMap.keySet()){             DestinationTemp.ID = ProductID;             DestinationTemp.No_of_Live_Curated_Products__c = DestinationIDToProductCountMap.get(ProductID);             DestinationUpdateList.add(DestinationTemp);         }         if(DestinationUpdateList.size() &gt; 0){             update DestinationUpdateList;         }           }           }
91517
public static void handleCaseComment(CaseComment caseComment) {    User[] users = [SELECT LastName FROM User WHERE Id = caseComment.CreatedById LIMIT 1]; }   This gives me the following error:  unexpected token: 'caseComment.CreatedById'   How do I use the value of the variable caseComment.CreatedById in a SELECT statement?
52784
This question appears to have been answered several times on here, but none of the solutions are working for me.  I have an Apex function defined like so:  @RemoteAction global static ActivityWrapper createActivity(Activity__c activity)   And when I call this Javascript function:  Controller.createActivity(     {ForWeek__c: "2014-04-21T08:00:00.000Z",      Notes__c: "sdfsdf",      Type__c: "Referral",      Id: null,      sObjectType: "Activity__c"}, callback);   I always get back this error message:  Visualforce Remoting Exception: Unexpected type for Controller.createActivity(Activity__c)   As far as I know this is all that is required, but I can't get past this.
120449
I am getting this error with the code below. I've looked into the other cases on here. In my case I am referring to a relationship name (__r) which I am assuming is pulling correctly. It's a field which is a lookup to User :   Agreement_CSH_to_be_completed_by__r  Here is the code which is giving me problems :   public void doManagedClients() {         addMsg('Starting processing of Managed Clients.');         Integer startSize = CSH_Data.size();          String SOQL = 'Select Id, OwnerId, Owner.UserName, Account__c, RecordTypeId, Name, Agreement_Client_Status_History__c ' +             'From Contract_Terms__c Where ' +             '   ( recordtypeid = \''+ ((String)A_N_Rectype).substring(0,15) + '\' ) and ' +                '   Agreement_Client_Status_History__c = \'Monthly\' ' +             'order by createddate desc nulls first' ; system.debug('#####333#### ');               addMsg(DEBUG,'Managed Query is: ' + SOQL + '\n');         for (Contract_Terms__c a: Database.Query(SOQL)) {             if (!a.Agreement_CSH_to_be_completed_by__r.isActive) {                 totalInactiveOwners++;                  addMsg('Account: ' + a.Name +  ', has an inactive owner.  Username: ' + a.Agreement_CSH_to_be_completed_by__r.isActive + '.');             } else {                             totalManagedCSHs++;                 addMsg(DEBUG,'Creating a Managed CSH for Account: ' + a);                 CSH_Data.add(new CSH_and_Share_Pair(a, createClientStatusHistory(a)));                 needflush(false);                 if (error) break;             }         }         needflush(true);         addMsg('End of Managed Clients.');           }   Is it just because I don't have a.Agreement_CSH_to_be_completed_by__r included in the SOQL ? I thought I got different errors for that, so I'm a little confused.  Thank you for your help.
64650
In an earlier question  I asked in general about the symbol table for an Apex class.  Using the Tooling API wrapper from  I am able to get part way there. But am unGodly confused.  If I go to the developer console, query editor, check the "Use Tooling API" box and run this query:  Select Id, Name, symbolTable FROM ApexClass Where Name Like '%NewCaseListController%'   I get back an ID, Name and [object Object] for the symbol table, meaning there is a symbol table object there.   But if I try the same query in Apex code in the execute anonymous window I get the error:   System.CalloutException: Web service callout failed: Unable to parse callout response. Apex type not found for element location   If I do this in Apex I can get a result back, and according to the code for the class the result should be of type ToolingAPIWSDL.QueryResult. The QueryResult should contain a member consisting of a list of sObject_x records sObject_x[], unless I am mis-reading what that means.  ToolingAPIWSDL.QueryResult result = tooley.query('select Id, Name from ApexClass WHERE Name Like \'NewCaseListController\'');   I can take the result and apparently put the sObject_x object in it like this:  List&lt;ToolingAPIWSDL.sObject_x&gt; objList = new List&lt;ToolingAPIWSDL.sObject_x&gt;(); for(Integer i = 0; i&lt;result.records.size(); i++){     objList.add(result.records[i]); }   At least that does not throw an error and I can write:     System.debug('objList: ' + objList[0]);  And get a result, but how do I access the symbol table? Or more to the point, how can I get a list of methods and variables? I am assuming the symbolTable is the only way?
57036
When I used to create the record in Event object it is showing error like:     Error: Invalid Data.   Apex trigger General_Event_Trigger caused an unexpected exception, contact your administrator: General_Event_Trigger: execution of BeforeINsert caused by: System.NullPointerException: Attempt to de-reference a null object: Class.EventClass.updateNewCustomFieldsEvent: line 369, column 1   Trigger code:  trigger General_Event_Trigger on Event (...) {     if (trigger.isBefore)     {         if (trigger.isInsert)         {             EventClass.updateNewCustomFieldsEvent(trigger.new);         }         else if (trigger.isUpdate)         {             EventClass.updateNewCustomFieldsEvent(trigger.new);         }     } }   Apex class:  public static void updateNewCustomFieldsEvent(List&lt;Event&gt; eventList) {     for (Event eve : eventList)     {         if (Administrators__c.getInstance().Update_field_Last_Modified_End_User__c)         {             String userIdString = eve.LastModifiedById;             eve.Last_Modified_By_End_User__c = userIdString.subString(0, 15);             eve.Last_Modified_Date_End_User__c = eve.LastModifiedDate;         }     } }
100093
I am using the following code in selenium, but I am not able to retrieve data from database. I am getting the errors "The result set has no current row"  My code is   public class Auto {      public static void main(String[] args) throws InterruptedException, SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException     {           Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");         System.out.println("Driver loaded");           Connection con=DriverManager.getConnection("jdbc:sqlserver://192.168.*****\\SQLEXPRESS/*****_DW/EPS:****;user=******;password=******; ");          System.out.println("Driver loadedd");       java.sql.Statement stmt= con.createStatement();     ResultSet rs=stmt.executeQuery("select * from [*****_DW].[dbo].dim_grantee ");      System.out.println("Query executed");      while (rs.next());     {         String Name=rs.getString("NAME");          System.out.println("Name is");     }   }
18923
I am trying to write a test for a trigger that is firing a future apex callout :  The trigger calls the callBillingService method from this class:  public class BillingCalloutService {     //Implement business and callout logic methods here     @Future(callout=true)     public static void callBillingService(List&lt;Id&gt; recordIds) {         List&lt;Project__c&gt; projects = [Select Id, ProjectRef__c,Billable_Amount__c from Project__c Where Id = :recordIds];          List&lt;Project__c&gt; projectsToUpdate = new List&lt;Project__c&gt;();          String username = ServiceCredentials__c.getValues('BillingServiceCredential').Username__c;         String password = ServiceCredentials__c.getValues('BillingServiceCredential').Password__c;          String auth = username + ':' + password;         String encodedAuth = EncodingUtil.base64Encode(Blob.valueOf(auth));          for(Project__c p : projects) {              BillingServiceProxy.InvoicesPortSoap11 service = new BillingServiceProxy.InvoicesPortSoap11();             service.inputHttpHeaders_x = new Map&lt;String, String&gt;();             service.inputHttpHeaders_x.put('Authorization', 'Basic ' + encodedAuth);              BillingServiceProxy.project project = new BillingServiceProxy.project();             project.username = username;             project.password = password;             project.projectRef = p.ProjectRef__c;             project.billAmount = p.Billable_Amount__c;              if(service.billProject(project).equals('ok')){                 projectsToUpdate.add(new Project__c(ProjectRef__c = p.ProjectRef__c, Status__c = 'Billed'));             }         }         shouldIRun.stopTrigger();         upsert projectsToUpdate ProjectRef__c;     } }   Error     Methods defined as TestMethod do not support Web service callouts   Test Class  @IsTest private class BillingCalloutServiceTest {      @IsTest     private static void testBillingCalloutService() {     Account a = new Account(Name = 'Acme');     insert a;     Opportunity o = new Opportunity(Name='Test', StageName='Submitted Project', AccountId=a.Id, Amount=1000, CloseDate=Date.Today());     insert o;     Project__c p = new Project__c(Status__c='Running',Start_Date__c=Date.Today(),End_Date__c=Date.Today(),Billable_Amount__c=10000,ProjectRef__c='projectX',Opportunity__c=o.Id);     insert p;      insert new ServiceCredentials__c(Name='BillingServiceCredential',Username__c='toto', Password__c='azerty');      Test.startTest();     Test.setMock(HttpCalloutMock.class, new BillingCalloutServiceMock());       p.Status__c = 'Billable';       update p;     Test.stopTest();     // runs callout and check results     p = [select Status__c from Project__c where id =: p.id];     System.assertEquals('Billed', p.Status__c);     }  }
55087
i am building a app which takes input from user and then search to a remote database(MySql).And then display the retrieved data on VisualForce page.One important note that my app will be distributable.  here is my controller class  public with sharing class Search  {    public String strTag {get;set;}   public String strlocation {get;set;}    public PageReference find() {              return null;   } }   Thanks in advance.  Updated  public with sharing class Search  {   public String strTag {get;set;} public String strlocation {get;set;}   public PageReference find() {             HttpRequest req = new HttpRequest();   HttpResponse res = new HttpResponse();   Http http = new Http();    req.setEndpoint('https://localhost/salesforce/');   req.setMethod('POST');     req.setCompressed(false);   req.setBody('key1=value1&amp;key2=value2');   req.setHeader('Content-Type', 'application/x-www-form-urlencoded');      try {     res = http.send(req);   } catch(System.CalloutException e) {     system.debug('Callout error: '+ e);   }   system.debug(res.getBody());      return null;  } }   I am getting below error now      error message System.CalloutException: Unauthorized endpoint, please check Setup->Security->Remote site settings. endpoint = localhost/salesforce
78597
I keep getting the System.NullPointerException: Attempt to de-reference a null object on my trigger at line 21. I've attempted to add != null to that line and I get an error too. Please see the code below.  trigger UpdateDMAAccount on Account (before insert, before update) { //get set of Postal Codes from leads to be inserted or updated Set&lt;String&gt; BillingpostalCodes = new Set&lt;String&gt;(); for(Account l : trigger.new){ if(l.BillingPostalCode != null){     BillingpostalCodes.add(l.BillingPostalCode);  } } if(BillingpostalCodes.size() &gt; 0){ //create Map of custom object records with Name (PostalCode) as key Map&lt;String,DMA_Value__c&gt; validBillingPostalCode = new Map&lt;String,DMA_Value__c&gt;(); for(DMA_Value__c obj : [SELECT Id, Name, DMA_Value__c FROM DMA_Value__c WHERE Name IN :BillingpostalCodes]){     validBillingPostalCode.put(obj.Name,obj); } for(Account l : trigger.new){     if((Trigger.isInsert || trigger.oldMap.get(l.Id).BillingPostalCode != l.BillingPostalCode) &amp;&amp; validBillingPostalCode.containsKey(l.BillingPostalCode)){          l.DMA__c = validBillingPostalCode.get(l.BillingPostalCode).DMA_Value__c;     }     else if(trigger.oldMap.get(l.Id).BillingPostalCode != NULL || l.BillingPostalCode &amp;&amp; !validBillingPostalCode.containsKey(l.BillingPostalCode)){         //blank value if new PostalCode does not match a record in the Map         l.DMA__c = Null;     }   }  } }
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?
94370
Now, before you say it: I did Google and my hbm.xml file is an Embedded Resource.   Here is the code I am calling:  ISession session = GetCurrentSession(); var returnObject =  session.Get&lt;T&gt;(Id);   Here is my mapping file for the class:  &lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"&gt;   &lt;class name="HQData.Objects.SubCategory, HQData" table="SubCategory" lazy="true"&gt;     &lt;id name="ID" column="ID" unsaved-value="0"&gt;       &lt;generator class="identity" /&gt;     &lt;/id&gt;      &lt;property name="Name" column="Name" /&gt;     &lt;property name="NumberOfBuckets" column="NumberOfBuckets"  /&gt;     &lt;property name="SearchCriteriaOne" column="SearchCriteriaOne" /&gt;      &lt;bag name="_Businesses" cascade="all"&gt;       &lt;key column="SubCategoryId"/&gt;       &lt;one-to-many           class="HQData.Objects.Business, HQData"/&gt;     &lt;/bag&gt;      &lt;bag name="_Buckets" cascade="all"&gt;       &lt;key column="SubCategoryId"/&gt;       &lt;one-to-many          class="HQData.Objects.Bucket, HQData"/&gt;     &lt;/bag&gt;    &lt;/class&gt; &lt;/hibernate-mapping&gt;   Has anyone run to this issue before?  Here is the full error message:   MappingException: No persister for:  HQData.Objects.SubCategory]NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName, Boolean throwIfNotFound)  in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:766 NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName)  in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:752 NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType)  in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Event\Default\DefaultLoadEventListener.cs:37 NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType)  in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:2054 NHibernate.Impl.SessionImpl.Get(String entityName, Object id)  in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1029 NHibernate.Impl.SessionImpl.Get(Type entityClass, Object id)  in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:1020 NHibernate.Impl.SessionImpl.Get(Object id)  in c:\CSharp\NH2.0.0\nhibernate\src\NHibernate\Impl\SessionImpl.cs:985 HQData.DataAccessUtils.NHibernateObjectHelper.LoadDataObject(Int32 Id)  in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQData\DataAccessUtils\NHibernateObjectHelper.cs:42 HQWebsite.LocalSearch.get_subCategory()  in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:17 HQWebsite.LocalSearch.Page_Load(Object sender, EventArgs e)  in C:\Development\HQChannelRepo\HQ Channel Application\HQChannel\HQWebsite\LocalSearch.aspx.cs:27 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436   Update, here's what the solution for my scenario was: I had changed some code and I wasn't adding the Assembly to the config file during runtime.
58610
This is a follow-up to .     When I click a link to an SE site in the Android app, it gives me an "open with" pop-up that has two options:         Chrome   Stack Exchange         I can then choose to open SE posts like this "Just once" or "Always."      The problem is that when I set the SE app to "always," and I click "open in browser,"   Except, the app crashes when trying to open it in browser.  LogCat (just right after selecting "Open in browser")  01-22 18:03:36.354: E/AndroidRuntime(16064): FATAL EXCEPTION: main 01-22 18:03:36.354: E/AndroidRuntime(16064): Process: com.stackexchange.marvin, PID: 16064 01-22 18:03:36.354: E/AndroidRuntime(16064): java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference 01-22 18:03:36.354: E/AndroidRuntime(16064):    at com.stackexchange.marvin.utils.Helpers.getNonMarvinViewIntent(Helpers.java:452) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at com.stackexchange.marvin.ui.question.QuestionDialog$1.onClick(QuestionDialog.java:39) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:1108) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at android.widget.AdapterView.performItemClick(AdapterView.java:310) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at android.widget.AbsListView.performItemClick(AbsListView.java:1145) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:3066) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at android.widget.AbsListView$3.run(AbsListView.java:3903) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at android.os.Handler.handleCallback(Handler.java:739) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at android.os.Handler.dispatchMessage(Handler.java:95) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at android.os.Looper.loop(Looper.java:148) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at android.app.ActivityThread.main(ActivityThread.java:5417) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at java.lang.reflect.Method.invoke(Native Method) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 01-22 18:03:36.354: E/AndroidRuntime(16064):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)   I suspect it's related to , but not sure.  Specs:   Device model: Nexus 5 Android version: Android 6.0.1 SE app version: 1.0.82 (beta) Installed browser: Chrome 47.0.2526.83 (latest at current writing)
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
57295
I have a Trigger that is referencing a class. It works in Dev, but now I am trying to create the test class in order to push it to production. I am trying to test that a new user is created. I keep getting the same error System.QueryException: List has no rows for assignment to SObject. The error seems to point to the class on line 9 where the Account is added. The goal of the code is when a new user is inserted, then a contact for that new user is created as well. Does someone have any ideas why this is happening? I've used the Query Editor to make sure that the record does exist, and it does, so I'm stumped. Thanks in advance for the help.   Trigger      trigger UserInsertContactInsert1 on User (after insert, after update) {      if(Trigger.isAfter &amp;&amp; Trigger.isInsert){         Set&lt;ID&gt; usrIds = new Set&lt;ID&gt;();          for(User u : Trigger.new){             usrIds.add(u.id);         }          UserContactSyncClass1.syncContact(usrIds);       }      if(Trigger.isAfter &amp;&amp; Trigger.isUpdate){          Set&lt;ID&gt; idSet = new Set&lt;ID&gt;();         Set&lt;ID&gt; idSet2 = new Set&lt;ID&gt;();          for(User u : trigger.new){             for(User r : trigger.old){                 if(u.ID == r.ID &amp;&amp; u.isActive==false &amp;&amp; r.isActive==true){                     idSet.add(u.ID);                 }                  if (u.ID == r.ID &amp;&amp; u.isActive==true &amp;&amp; r.isActive==false) {                     idSet2.add(u.ID);                 }              }         }          UserContactSyncClass1.InactiveContact(idSet);         UserContactSyncClass1.ActivateContact(idSet2);     } }   Class  public class UserContactSyncClass1 {      @future     public static void syncContact(Set&lt;Id&gt; userSet){         List&lt;Contact&gt; cList = new List&lt;Contact&gt;();         List&lt;User&gt; userList = [Select ID, FirstName, LastName, Email, Phone, True_Market_Unit__c, True_Market_Name__c FROM User WHERE ID IN :userSet];         List&lt;String&gt; mList = new List&lt;String&gt;();         List&lt;String&gt; mktList = new List&lt;String&gt;();         **Account acc = [SELECT Id, Name FROM Account WHERE Name = 'Company Users' Limit 1];**          // Loop through Users, to get List of True Market Number         for(User usr : userList){             mList.add(usr.True_Market_Unit__c);                 }          // Use the True Market Number and Match to the True Market Number in Markets         for(Market__c mkt : [SELECT Name, Unit_Number__c FROM Market__c WHERE Unit_Number__c IN :mList]){             mktList.add(mkt.Name);           }          for(User usr : userList){             for(String mk : mktList){                 usr.True_Market_Name__c = mk;             }             System.debug(usr.True_Market_Name__c);         }          for(User u : userList){             cList.add(new Contact(FirstName=u.FirstName, LastName=u.LastName, User_True_Market_Name__c=u.True_Market_Name__c, Email=u.Email, Phone=u.Phone, OwnerID=u.ID, Related_User__c=u.Id, AccountId = acc.Id));         }          upsert cList;     }   Test Class Method with the Error  public static testMethod void validateNewUser(){          Profile p = [SELECT id FROM Profile WHERE Name='System Administrator'];          User u = new User(             FirstName = 'test',              LastName= 'last_test',              Email='test323232@test.com',              Phone='111-111-1111',              True_Market_Unit__c='1111',              alias = 'test',              EmailEncodingKey='UTF-8',             ProfileId = p.Id,             LanguageLocaleKey='en_US',             LocaleSidKey='en_US',              TimeZoneSidKey='America/Los_Angeles',             UserName = 'test323232@test.com'          );          System.runAs(u){             System.assertEquals('111-111-1111', u.Phone);         }      }   Updated Solution  Turns out even though my User never referenced the account, I still needed to insert it into my test class, with the Name='Company Users' from my SOQL query. Thanks everyone for all the help.
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;     } }