I have tried to understand what is causing my getTeamId() method in my entity return null, but I can't seem to crack the code. I have attached my adapter class, entity class and the exception thrown.       Entity Class TeamEntity  @SerializedName("idTeam")     private String teamId;         public String getTeamId() {             return teamId;         }          public void setTeamId(String teamId) {             this.teamId = teamId;     }   And in my adapter class I have the following, it says team is null do i need to add something to it?  public class MatchAdapter extends RecyclerView.Adapter&lt;MatchAdapter.ViewHolder&gt; {     private Context context;     private TeamEntity team;     private List&lt;MatchEntity&gt; matchList;      public MatchAdapter(Context context, TeamEntity teamEntity) {         this.context = context;         this.team = teamEntity;         matchList = new ArrayList&lt;&gt;();     }      public void setList(List&lt;MatchEntity&gt; matchList) {         this.matchList.addAll(matchList);         Collections.sort(this.matchList); //date order         notifyDataSetChanged();     }      public void updateMatch(MatchEntity match) {         matchList.set(matchList.indexOf(match), match);         notifyItemChanged(matchList.indexOf(match));     }      @NonNull     @Override     public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {         View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.display_match_items, parent, false);         return new ViewHolder(view);     }      @Override     public void onBindViewHolder(@NonNull ViewHolder holder, int position) {         MatchEntity match = matchList.get(position);         holder.bind(match);     }      @Override     public int getItemCount() {         return matchList.size();     }     @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) {     MatchEntity match = matchList.get(position);     holder.bind(match); }       void bind(MatchEntity match) {                  String homeTeam = match.getHomeTeam() != null ? match.getHomeTeam() : "";                   if (team.getTeamId().equals(match.getIdGuestTeam())) {                     homeTextView.setText(homeTeam);                   } else {                     homeTextView.setText(guestTeam);                  }   // Stack Trace  java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.sportsapp.data.room.entities.TeamEntity.getTeamId()' on a null object reference         at com.sportsapp.presentation.ui.adapters.MatchAdapter$ViewHolder.bind(MatchAdapter.java:118)         at com.sportsapp.presentation.ui.adapters.MatchAdapter.onBindViewHolder(MatchAdapter.java:59)         at com.sportsapp.presentation.ui.adapters.MatchAdapter.onBindViewHolder(MatchAdapter.java:27)
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?
4404
Im getting above error when i was trying to run my test class. In my test class i will create an Account, Contact. And this contact id will be used in my original code to create Community user.  I noticed following help article from SFDC. But couldn't figure out how to achieve.   Here they asked to create User on the Test class and Runas this user. But in my case, the community user will be created in the code. Please share any thoughts.  Here is the detailed exception,     System.DmlException: Insert failed. First exception on row 0; first   error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, caused by:   System.DmlException: Insert failed. First exception on row 11; first   error: UNKNOWN_EXCEPTION, portal account owner must have a role: []
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
109761
I have getting the below JSON on using JSON.serialize  [ {   "lname" : "Singh",   "hcpZipCode" : null,   "hcpState" : null,   "hcpEmail" : "test@test.com",   "hcpCity" : null,   "hcpAddLine1" : null,   "fname" : "Abhey",   "countryCode" : "AUS" } ]   I don't know why this '[' is coming at the begining.I don't need this '[' at the begining due to which I am getting System.JSONException: Malformed JSON: Expected '{' at the beginning of object  code     public PageReference step2() {         string JSONstr='';        List&lt;HCPRequest&gt; conWrapList = new List&lt;HCPRequest&gt;();        HCPRequest tempcontactWrapper = new HCPRequest();        tempcontactWrapper.fname='Abhey';        tempcontactWrapper.lname='Singh';        tempcontactWrapper.countryCode='AUS';        tempcontactWrapper.hcpEmail=contact.Email;         conWrapList.add(tempcontactWrapper);          JSONstr = JSON.serializePretty(conWrapList);         System.debug('\n******'+JSONstr +'\n******');          String clientId = 'xy';         String clientSecret = 'x';          //We can also store our username password in custom setting.         String username='x';//salesforce username          String password='x';//password+securitytoken         // Generating the Access Token         HttpRequest req = new HttpRequest();         req.setMethod('POST');         req.setEndpoint('https://test.salesforce.com/services/oauth2/token');// this is the OAuth endpoint where this request will be hit         req.setBody('grant_type=password&amp;client_id='+clientId+'&amp;client_secret='+clientSecret+'&amp;username='+username+'&amp;password='+password);          Http http = new Http();         HTTPResponse res = http.send(req);         String str = res.getBody();         wrapObj = (Wrapper)Json.deserialize(str,Wrapper.class);         accessToken = wrapObj.access_token;         instanceUrl = wrapObj.instance_url;          HttpRequest req1 = new HttpRequest();         string response='';         req1.setMethod('POST');         //req.setEndpoint(wrapObj.instance_url+'/services/apexrest/Account/getAccountById?name=champaKAli');         string EndPt = 'y';         string email='test@test.com';         req1.setEndpoint(EndPt);         req1.setHeader('Authorization', 'OAuth '+wrapObj.access_token);          req1.setHeader('Content-Type', 'application/json');          //req1.setBody('{"request":{"lname" : "Singh","hcpZipCode" : null,"hcpState" : null,"hcpEmail" : "test@test.com","hcpCity" : null,"hcpAddLine1" : null,"fname" : "Abhey","countryCode" : "AUS"}}');          req1.setBody('{"request":'+JSON.Serialize(conWrapList)+'}');          //req.setBody('{"request": {"countryCode": "AUS","hcpEmail" : ""+email}}');          //req.setTimeout(60000);             //req.setHeader('Content-Length', '0');         Http http1 = new Http();         HTTPResponse res1 = http1.send(req1);          System.debug('***Response***** ' + res1.getBody());         if(res1.getBody()!=null)         {             response=res1.getBody();             HCPResponse saj=(HCPResponse)JSON.deserialize(response,HCPResponse.class);           System.debug('***Response came full***** ' + saj);            System.debug('***Response came***** ' + saj.accList);             for(HCPResponseDetail s :saj.accList)            {            System.debug('***Response email***** ' + s.hcpEmail);            System.debug('***Response add2***** ' + s.hcpAddrLine2);            contact.Address1_Line2__c=s.hcpAddrLine2;            }           //return response;         //string methodcall=methodGet(JSONstr);               return Page.opptyStep2CustomReg;         }
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
106099
I'm working on developing a test class for my apex. I'm stuck with creation of Contract records contractnumber field. In test class, I use the following code:     Contract c = new Contract();     c.Name = 'Test Contract';     c.AccountId = acc.Id;     c.Status = 'Draft';     insert c;     //I'm creating a draft contract and then activating it.     c.status  = 'Activated';     update c;     system.debug('contract debug:'+c.contractnumber);  Contractnumber field on object is Autonumber, but in the log I get null for contractnumber. I see the whole contract record is created with null ContractNumber. What am I doing wrong?
76549
For example  Drupal\Core\Entity\Entity::id() returns $this-&gt;id(or NULL) Drupal\Core\Entity\ContentEntityBase::id() returns $this-&gt;id-&gt;value Drupal\Core\Entity\ContentEntityBase::uuid() returns $this-&gt;get('uuid')-&gt;value Drupal\node\Entity\Node::id() returns $this-&gt;get('nid')-&gt;value  Also in some methods there are setValue() and getValue() utilised but sometimes there are just $this-&gt;field-&gt;value. So what is the reason for this inconsistent behavior? From my understanding all the &quot;fields&quot; are TypedData fields hence the setValue() and getValue() methods should be used instead of directly access $this-&gt;field-&gt;value. Besides it's strange because $value is private.
121895
I have a trigger and a class that seem to be causing an insert fail in Dataloader.  I am trying to insert 200 records to see if an error is generated before moving these to production. I'm just inserting the mandatory fields such as Name, Owner, Market, Customer_Success_Manager__c, and Business Unit.   Each time I get an error:     UpdateCSMTeam:execution of AfterInsertcaused by: System.DmlException:   Insert failed. First exception on row 0 with id01MJ0000009gXthMAE;   first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an   insert call: [Id]Class.UpdateCSM.updateTeamMem . I've listed the class   and trigger below.   APEX CLASS  public class UpdateCSM {             public static void updateTeamMember(List&lt;Account&gt; accounts) {                     List&lt;AccountShare&gt; ashareLIST = new List&lt;AccountShare&gt;();                     List&lt;AccountTeamMember&gt; ATM = new List&lt;AccountTeamMember&gt;();                    Set&lt;String&gt; rmMember = new Set&lt;String&gt;();                     Map&lt;ID, ID&gt; acctToBRepMap = new Map&lt;ID, ID&gt;();                      for(Account a:accounts){                              AccountShare caSharingRule = new AccountShare();                                caSharingRule.AccountId = a.Id;                                caSharingRule.OpportunityAccessLevel = 'Edit';                                caSharingRule.CaseAccessLevel = 'Edit';                                caSharingRule.AccountAccessLevel = 'Edit';                                caSharingRule.UserOrGroupId = a.Customer_Success_Manager__c;                                ashareLIST.add(caSharingRule);                                    if(a.Customer_Success_Manager__c!= null){                                   AccountTeamMember Teammemberad=new AccountTeamMember();                 Teammemberad.AccountId=a.id;                 Teammemberad.UserId=a.Customer_Success_Manager__c;                 Teammemberad.TeamMemberRole = 'Customer Success Manager';                                   ATM.add(Teammemberad);                             if(!ATM.isEmpty()){                                    insert ATM;                                              insert ashareLIST;                                                         if(a.Customer_Success_Manager__c==null){                                            list&lt;AccountTeamMember&gt; ratm = [SELECT UserId                                                                             FROM AccountTeamMember                                                                             WHERE (TeamMemberRole = 'Customer Success Manager')                                                          AND AccountId =:a.id];                                             if(ratm.size()&gt;0)                                                 delete ratm;                                        }                                    }                                 }                            }                         }                    } ...   APEX TRIGGER  trigger UpdateCSMTeam on Account (After update, After insert){         UpdateCSM.updateTeamMember(trigger.new); }
121697
I am currently making a mod for Minecraft but I have come to a stop because I am lacking in some knowledge. I need to get data for the entity I am looking at, which I believe requires the use vectors, something I don't really know how to use.   How would I achieve this? Some stuff that I think could help are mc.thePlayer.getLookVector() which returns the normalized vector of the user and mc.theWorld.loadedEntityList, which  is a List with all the loaded currently loaded entities.
39802
I was writing test classes for my apex Rest Service that I had built for an Ipad app.  I noted some very interesting things while experimenting. Before doing anything, I just did a google search and found an interesting blog post by Jeff.    @RestResource(urlMapping='/v.9/member/*/results/*')  global with sharing class MemberRestSvc {  @HttpGet  global static ReturnClass doGet() {  String[] uriKeys = RestContext.request.requestURI.split('/'); // get the member name from the uri String memberName = uriKeys.get(uriKeys.size()-3);  // do awesome programming stuff here &amp; catch any exceptions try {    List&lt;Contact&gt; contacts = [Select Id From Contact where member_name__c = :memberName];   return new ReturnClass('true', 'Query executed successfully.', contacts);  } catch (Exception e) {   return new ReturnClass('false', e.getMessage(), null); }   }   global class ReturnClass {  global String success; global String message; global List&lt;Contact&gt; records;    global ReturnClass(String success, String message, List&lt;Contact&gt; records) {   this.success = success;   this.message = message;   this.records = records;  }  }  }   And here is the test class  @isTest private class Test_MemberRestSvc {  static { // setup test data   }  static testMethod void testDoGet() {  RestRequest req = new RestRequest();  RestResponse res = new RestResponse();  req.requestURI = 'https://cs9.salesforce.com/services/apexrest/v.9/member/me/results/today';   req.httpMethod = 'GET'; RestContext.request = req; RestContext.response = res;  MemberRestSvc.ReturnClass results = MemberRestSvc.doGet();  System.assertEquals('true', results.success); System.assertEquals(10, results.records.size()); System.assertEquals('Query executed successfully.', results.message);  }  }   I just commented a few lines and ran and it. I still achieved enough test coverage so my question is why do I need to simply instantiate the Rest request and response objects since I am directly calling the class?    @isTest   private class Test_MemberRestSvc {    static {     // setup test data     }  static testMethod void testDoGet() {  /*RestRequest req = new RestRequest();  RestResponse res = new RestResponse();  req.requestURI =    'https://cs9.salesforce.com/services/apexrest/v.9/member/me/results/today';   req.httpMethod = 'GET'; RestContext.request = req; RestContext.response = res; */Commented the code meant for REST apex intialization and merely calling the method!!  MemberRestSvc.ReturnClass results = MemberRestSvc.doGet();  System.assertEquals('true', results.success); System.assertEquals(10, results.records.size()); System.assertEquals('Query executed successfully.', results.message);  }  }   Can someone explain this behavior? Also what are the best practices for writing Test classes for apex Rest services?
16225
Why does it (apparently) make a difference whether I pass null as an argument directly, or pass an Object that I assigned the value null?  Object testVal = null; test.foo(testVal);    // dispatched to foo(Object) // test.foo(null);    // compilation problem -&gt; "The method foo(String) is ambiguous"     public void foo(String arg) { // More-specific     System.out.println("foo(String)"); }  public void foo(Object arg) { // Generic     System.out.println("foo(Object)"); }   In other words, why is the (commented-out) second call to foo(...) not dispatched to foo(Object)?  Update: I use Java 1.6. I could compile Hemal's code without problems, but mine still doesn't compile. The only difference I see is that Hemal's methods are static while mine are not. But I really don't see why this should make a difference...?  Update 2: Solved. I had another method foo(Runnable) in my class, so the dispatcher couldn't unambiguously select the single most specific method. (See my comment in Hemal's second answer.) Thanks everyone for your help.
18034
when i try to save the following code, i got the error below. Following same instructions given in this link, but still errors. Am i doing anything wrong here? please suggest.    @isTest private class WebSvcCalloutTest {     @isTest static void testEchoString() {         Account a = new Account(name='Tester',SAP_KUNNR__c='1172');         insert a;                       // This causes a fake response to be generated         Test.setMock(WebServiceMock.class, new WebServiceMockImpl());      } }   Error:  Save error: Method does not exist or incorrect signature: Test.setMock(Type, WebServiceMockImpl)    WebSvcCalloutTest.cls         @isTest global class WebServiceMockImpl implements WebServiceMock {    global void doInvoke(            Object stub,            Object request,            Map&lt;String, Object&gt; response,            String endpoint,            String soapAction,            String requestName,            String responseNS,            String responseName,            String responseType) {          sapComDocumentSapSoapFunctionsMcS.Z_GSSMWFM_HNDL_EVNTRQST00 sap1 = new sapComDocumentSapSoapFunctionsMcS.Z_GSSMWFM_HNDL_EVNTRQST00();                Map&lt;String,String&gt; mapSAP = new Map&lt;String,String&gt; {};         sapComDocumentSapSoapFunctionsMcS.ZgssmbstDatarcrd01 req = new sapComDocumentSapSoapFunctionsMcS.ZgssmbstDatarcrd01();               sapComDocumentSapSoapFunctionsMcS.ZGssmwfmHndlEvntrqst00Response_element ret =  sap1.ZGssmwfmHndlEvntrqst00('',req);         response.put('response_x', ret);     } }
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?
107801
I posted the code below to the Sun developers forum since I thought it was erroring (the true error was before this code was even hit).  One of the responses I got said it would not work and to throw it away.  But it is actually working.  It might not be the best code (I am new to Java) but is there something inherently "wrong" with it?   =============  CODE:   private static void ImportFromCsvToAccessTable(String mdbFilePath, String accessTableName  , String csvDirPath , String csvFileName ) throws ClassNotFoundException, SQLException {      Connection msConn = getDestinationConnection(mdbFilePath);     try{          String strSQL = "SELECT * INTO " + accessTableName + " FROM [Text;HDR=YES;DATABASE=" + csvDirPath + ";].[" + csvFileName + "]";         PreparedStatement selectPrepSt = msConn.prepareStatement(strSQL );         boolean result = selectPrepSt.execute();                 System.out.println( "result = " + result );      } catch(Exception e) {         System.out.println(e);     } finally {         msConn.close();     } }
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?
120685
It seems to me that a lot of my debugging time is spent chasing down null-reference exceptions in complex statements. For instance:  For Each game As IHomeGame in _GamesToOpen.GetIterator()   Why, when I get a NullReferenceException, can I get the line number in the stack trace, but not the name of the object that equals null. In other words, why:  Object reference not set to an instance of an object.   instead of  _GamesToOpen is not set to an instance of an object.   or  Anonymous object returned by _GamesToOpen.GetIterator() is null.   or  game was set to null.   Is this strictly a design choice, meant to protect the anonymity of the code or is there a compelling reason in compiler design not to include this information in the debug-time exception?
90464
We noticed that lots of bugs in our software developed in C# (or Java) cause a NullReferenceException.  Is there a reason why "null" has even been included in the language?  After all, if there were no "null", I would have no bug, right?  In other words, what feature in the language couldn't work without null?