I basically try to save the current state of mRecyclerView into a static Parcelable variable to keep it safe onPause and restore it to the mRcyclerView onResume.  Here is my static variable's class:  public class MySavedState { private static MySavedState ourInstance = new MySavedState();  private Parcelable state;  static MySavedState getInstance() {     if(ourInstance == null){         ourInstance = new MySavedState();     }     return ourInstance; }  private MySavedState() { }  public Parcelable getState() {     return state; }  public void setState(Parcelable state) {     this.state = state; }   }  And here is the line where I try to set a value:  @Override public void onPause() {     super.onPause();      Parcelable newState = mRecyclerView.onSaveInstanceState();     state.setState(newState);   }   And the error message:  java.lang.RuntimeException: Unable to pause activity {com.gunaya.tasmaew/com.gunaya.tasmaew.Controller.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.gunaya.tasmaew.Model.MySavedState.setState(android.os.Parcelable)' on a null object reference                   at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3745)                   at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3704)                   at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3679)                   at android.app.ActivityThread.access$1100(ActivityThread.java:177)                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)                   at android.os.Handler.dispatchMessage(Handler.java:102)                   at android.os.Looper.loop(Looper.java:145)                   at android.app.ActivityThread.main(ActivityThread.java:5951)                   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:1388)                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.gunaya.tasmaew.Model.MySavedState.setState(android.os.Parcelable)' on a null object reference                   at com.gunaya.tasmaew.Controller.mListFragment.onPause(mListFragment.java:117)   And as an extra question, i keep having this error message in my debugger:  ((Bundle)parce).mClassLoader = Cannot find local variable 'parce'   Thank you very much for your time guys.
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?
92671
public class ExampleClass {       public static void publishCaseUpdateNotifications(List&lt;Case&gt; cases) {     List&lt;Case_Updated__e&gt; notifications = new List&lt;Case_Updated__e&gt;();     for (Case c: cases) {         notifications.add(new Case_Updated__e(             Case__c = (String)c.Id,             CreatedByName__c = UserInfo.getName(),             CaseNumber__c = c.CaseNumber         ));     }       List&lt;Database.SaveResult&gt; results = EventBus.publish(notifications);      for (Database.SaveResult result : results) {         if (!result.isSuccess()) {             for (Database.Error error : result.getErrors()) {                 System.debug('Error returned: ' +                     error.getStatusCode() +' - '+                     error.getMessage());             }         }       }      }    }   My Test Class: getting error   @isTest   public class ExampleTestClass {    @isTest   static void testClassforExample(){         Case testcase = new Case(Subject ='Test',);      list&lt;Case_Updated__e&gt; caseUpdate =      ExampleClass.publishCaseUpdateNotifications(testcase );       }      }   My Error is Method does not exist or incorrect signature: void publishCaseUpdateNotifications(Case) from the type ExampleTestClass   Please suggest me how to resolve this error.     trigger Cases on Case (after insert) { if(Trigger.isAfter) {     System.debug('I will be replaced shortly!'); }  }   Do we need test class for above trigger. Please suggest me too
11867
My singleton accessor method is usually some variant of:  static MyClass *gInstance = NULL;  + (MyClass *)instance {     @synchronized(self)     {         if (gInstance == NULL)             gInstance = [[self alloc] init];     }      return(gInstance); }   What could I be doing to improve this?
112290
This code throws a NullReferenceException when it calls ExecuteScalar:  selectedPassengerID = 0;  //SqlCommand command = GenericDataAccess.CreateCommand();   // 2nd test string connectionString = ""; SqlConnection conn;  connectionString = ConfigurationManager.     ConnectionStrings["ConnST-MHM"].ConnectionString; conn = new SqlConnection(connectionString); SqlCommand command = new SqlCommand(); command.CommandType = CommandType.StoredProcedure ; command.Connection = conn; command.CommandText = "SearchForPassenger";  SqlParameter param;  param = command.CreateParameter(); param.ParameterName = "@name"; param.Value = pName; // Session[""]; param.DbType = DbType.String; command.Parameters.Add(param);  param = command.CreateParameter(); param.ParameterName = "@flightDate"; param.Value = date;  param.DbType = DbType.String; command.Parameters.Add(param);  param = command.CreateParameter(); param.ParameterName = "@ticketNo"; param.Value = ticketNumber;  param.DbType = DbType.Int32; command.Parameters.Add(param);  int item;  command.Connection.Open(); item = (int)command.ExecuteScalar();
68495
I am getting this error:     SObject row was retrieved via SOQL without querying the requested   field: Contact.Account   Controller:  public class WrapperAccountCtrl {      public List&lt;Account&gt; acclist{get;set;}     public List&lt;Contact&gt; conlist{get;set;}      public List&lt;MyWrapper&gt; wap{get;set;}      public WrapperAccountCtrl()      {         acclist=[Select id,name from Account];          conlist=[Select id,name,AccountID  from contact where AccountID IN:acclist];          system.debug('Size----'+conlist.size());           wap=new List&lt;MyWrapper&gt;();           for(integer i=0;i&lt;acclist.size();i++)          {              wap.add(new MyWrapper(conlist,acclist[i]));          }     }      public class MyWrapper     {          public Account accn{get;set;}          public List&lt;Contact&gt;conrec{get;set;}          public MyWrapper(List&lt;Contact&gt; con,Account acc)         {             accn=acc;             conrec=con;             }     } }   VF Page:  &lt;apex:page controller="WrapperAccountCtrl" sidebar="false"&gt;       &lt;apex:form &gt;          &lt;apex:pageBlock &gt;              &lt;apex:pageBlockTable value="{!conlist}" var="c"&gt;                  &lt;apex:column value="{!c.account.Name}"/&gt;              &lt;/apex:pageBlockTable&gt;          &lt;/apex:pageBlock&gt;      &lt;/apex:form&gt;  &lt;/apex:page&gt;
86546
I have been trying to integrate Google Shortener API into my salesforce org. I wrote a class to make the call out, but am having difficulty bringing the value back into the record. I have a custom object called "referral_advocate__c" with a field called "Short_URL__c". Anytime the field "unique_ID__c" has a value, I am wanting to send this value with a static URL to google shortener and then save the response value to "referral_advocate__c.short_URL__c" on the record. This is the class to make the call out:  public class URLshort {  final string urls = 'https://www.myurl.com'; referral_advocate__c adv = new referral_advocate__c();  @future(callout = true) public static void URLshortner() {      HttpRequest req = new HttpRequest();     HttpResponse res = new HttpResponse();     Http http = new Http();      req.setEndpoint('https://www.googleapis.com/urlshortener/v1/url?key=myapikey');     req.setMethod('POST');     req.setHeader('Content-Type','application/json');            req.setBody('{"longUrl":+urls + adv.unique_reference_number_c}');       try {         res = http.send(req);         System.debug(res.getBody());     } catch(System.CalloutException e) {         System.debug('Callout error: '+ e);         System.debug(res.toString());     }   }  }   The after insert trigger on "referral_advocate__c" I wrote is not firing correctly. How do I return the results from this class and update the field "short_URL__C" with the returned value from a trigger?
61126
I am getting java.lang.NullPointerException while executing my test case , I am using Page Object Modle with PageFactory ,following are the code snippets  LoginPageObjec.java  public class LoginPageObjects {      @FindBy(xpath=".//*[@id='userName']")     private WebElement email;      @FindBy(xpath=".//*[@id='password']")     private WebElement password;      @FindBy(xpath=".//*[@id='loginFormSubmit']")     private WebElement loginBtn;      public void EnterUserName(String userName)     {         email.sendKeys(userName);     }      public void EnterPassword(String pass)     {         password.sendKeys(pass);     }      public void clickLogin()     {         loginBtn.click();     }   }   LoginTC.java  public class LoginTC extends BasePage{     private WebDriver driver;      @Test     public void login()     {         LoginPageObjects loginPage = PageFactory.initElements(driver, LoginPageObjects.class);         loginPage.EnterUserName("test.hr@domin.com.pk");         loginPage.EnterPassword("test");         loginPage.clickLogin();     } public void login1()         {             LoginPageObjects loginPage = PageFactory.initElements(driver, LoginPageObjects.class);             loginPage.EnterUserName("test.hr@domin.com.pk");             loginPage.EnterPassword("test");             loginPage.clickLogin();         }  }   BasePage.java  public class BasePage {     private WebDriver driver;      @BeforeMethod       public void initializeBrowser() {      driver=new FirefoxDriver();      driver.navigate().to("https://nexthrm-dev.vteamslabs.com/");      driver.manage().window().maximize();      }     @AfterMethod     public void closeBrowser()     {         driver.close();     }  }   I've extended BasePage class to utilize the (initialBrowser &amp; closeBrowser) functions in my test case but its producing nullpointer exception if I copy both of the functions (initialBrowser &amp; closeBrowser) into my LoginTC (testcase class) it works like charm but I dont want this redundant code i.e((initialBrowser &amp; closeBrowser) for all my testcases class could anyone explain why I am getting nullpointer exception
7576
I have a lookup to a custom object called Project on my Opportunity object. I am trying to write a trigger that updates an Active, Awarded, and Title on the Project object whenever the Active, Awarded, or Title field is updated on Opportunity based some on more logic that isn't in my code below. This is my first trigger and needing a little help due to a NullPointerException where I try to set Project__r.Active__c = true. Any thoughts?      trigger ProjectFieldsTrigger on Opportunity (before insert, before update) {       //List&lt;Opportunity&gt; opp = [SELECT Name, Active__c, Funded__c, Title__c, Project__r.Name, Project__r.Active__c, Project__r.Awarded__c      //  FROM Opportunity WHERE Id IN :Trigger.New];      for(Opportunity o: Trigger.New){          if(o.Project__c != null){              if(o.Active__c == 'Y'){                 o.Project__r.Active__c = true;             }      }  }
77080
This may sound repititve question. But the error incurs after following multiple links found like:  and .  The controller:  public with sharing class SFLoginCtrlr {     public static HTTPResponse getResp(String loginCred){         Map&lt;String, Object&gt; mapLoginCred = (Map&lt;String, Object&gt;)JSON.deserializeUnTyped(loginCred);         String username = ''+mapLoginCred.get('username');         String password = ''+mapLoginCred.get('password');         HttpRequest req = new HttpRequest();         req.setMethod('POST');            req.setTimeout(60000);         req.setEndpoint('https://www.salesforce.com/services/Soap/u/29.0');         req.setHeader('Content-Type', 'text/xml;charset=UTF-8');                 req.setHeader('SOAPAction', '""');         req.setBody('&lt;Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"&gt;&lt;Header/&gt;&lt;Body&gt;&lt;login xmlns="urn:partner.soap.sforce.com"&gt;&lt;username&gt;' +username+ '&lt;/username&gt;&lt;password&gt;' + password + '&lt;/password&gt;&lt;/login&gt;&lt;/Body&gt;&lt;/Envelope&gt;');                 HttpResponse res = new Http().send(req);         return res;     } }   The mock class:  @isTest global class ExampleCalloutMock implements HttpCalloutMock{   global HttpResponse respond(HTTPRequest req){     HttpResponse res = new HttpResponse();     res.setStatus('OK');     res.setStatusCode(200);     res.setBody('SUCCESS');     return res;   } }   The test class:  @isTest private class SFLoginCtrlrTest{     static testMethod void SFLoginCtrlrTestMethod(){         Test.startTest();          Test.setMock(HttpCalloutMock.class, new ExampleCalloutMock());          Map&lt;String, String&gt; logincred = new Map&lt;String, String&gt;();         logincred.put('username', 'dummy@user.com');         logincred.put('password', 'notapassword');          SFLoginCtrlr.getResp(JSON.serialize(logincred));          Test.stopTest();     } }   The error received while running test class:     Methods defined as TestMethod do not support Web service callouts   Not sure, where is the issue...
103112
When and why would somebody do the following:  doSomething( (MyClass) null );   Have you ever done this? Could you please share your experience?
84621
I'm struggling to test a class with pagereference. Following is the class...  public with sharing class redirectOrderPartner{  public String currentRecordId {get;set;} public orders__c orderId {get;set;}  public redirectOrderPartner(ApexPages.StandardController controller) {      }     Public Pagereference go(){      currentRecordId  = ApexPages.CurrentPage().getparameters().get('orderid');      system.debug('---currentRecordId  ---'+currentRecordId  );     orderId = [select id from orders__c where name =: currentRecordId limit 1];      system.debug('---orderid---'+orderId);      PageReference pageRef = new PageReference('/apex/OrderTrackingClass?id='+orderId.id);     pageRef.setRedirect(true);     return pageRef;    }   }   Following is what I tried....    @isTest  public class redirectOrderPartner_TEST  {             static testMethod void Test(){            Account acc = new Account(Name='ABC Corp.');           insert acc;            orders__c tempOrder = new orders__c(name = '0001234567', account__c = acc.id );           insert tempOrder;            Test.startTest();            PageReference pageRef = Page.redirectOrderPartner;           Test.setCurrentPage(pageRef);            ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(tempOrder);           ApexPages.currentPage().getParameters().put('Id',tempOrder.name);           PW_redirectOrderPartner ec = new redirectOrderPartner(sc);           ec.go();                                   Test.stopTest();       }   } I get the following error message on testing..     System.QueryException: List has no rows for assignment to SObject   What am I missing? Thanks
96022
I had the following exception thrown at me when trying to process more than one selected records via a custom button in the list view.    Class Code  global class MerchandiseInventoryClass {      webservice static void ConverttoInventory(String[] merchandise_id)    {        //Convert Merchandise collection into Inventory Collection...         Merchandise__c[] merchandise_collection = [SELECT ID,Author__c,Book_Title__c,Edition__c,Publisher__c,Total_Merchandise_QtyTotal_Qty__c,Status__c FROM Merchandise__c WHERE ID = :merchandise_id];          Inventory__c i = new Inventory__c(); //Line 1        List&lt;Inventory__c&gt; newInventory = new List&lt;Inventory__c&gt;();        for(Merchandise__c m : merchandise_collection )        {            if(m.Status__c !='Fully Converted')            {            i.Author__c = m.Author__c ;            i.Book_Title__c = m.Book_Title__c;            i.Edition__c = m.Edition__c;            i.Publisher__c = m.Publisher__c;            i.Qty_Available__c = m.Total_Merchandise_QtyTotal_Qty__c;            i.Merchandise__c = m.Id;            m.Uninventoried_Qty__c = 0;            m.Status__c = 'Fully Converted';            newInventory.add(i);            }        }        insert newInventory;        update merchandise_collection;    }  }   By moving the Line 1 to within the for loop solved the issue for me.  Thanks to this post (refer the Best Answer in that post)    What puzzles me is that WHY i have to instantiate "i" for every iteration within the loop.  Why the list collection ("newInventory") is complaining that are duplicate elements and why should it even confuse in the first place when I am performing an "insert" even ?
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 !!');             }         }     }
7315
Recently, apps that are fine an hour ago now crash when I open them. The crash report message seems to be caused by a null pointer exception (NPE) in com.google.android.trichromelibrary. Apps affected for me:  Gmail Dashlane  Is it just me, or is there actually something wrong with the library? How can I fix these affected apps? Crash report: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** Build fingerprint: 'Xiaomi/polaris/polaris:10/QKQ1.190828.002/20.9.4:user/release-keys' Revision: '0' ABI: 'arm64' Timestamp: ... pid: ..., tid: ..., name: com.dashlane &gt;&gt;&gt; com.dashlane &lt;&lt;&lt; uid: ... signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x0 Cause: null pointer dereference          ...  backtrace:     #00 pc 00000000038621f0 /data/app/ com.google.android.trichromelibrary 438909034-YaxP9ttrIDcQBfleP5vm7Q==/base.apk! libmonochrome_64.so (offset 0x646000) (BuildId: ... )  (click  for the screenshot of the bug report)
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.
12247
I have the following code:  List&lt;MobileElement&gt; messages = driver.findElements (By.id ("body_bubble")); //find all messages MobileElement lastMessage = messages.get (messages.size () - 1); //get last message  // xpath query to check if the message is delivered String xpathDeliveryStatus = ".//*[contains(@resource-id, 'delivered_indicator') or contains(@resource-id, 'read_indicator') or contains(@resource-id, 'sent_indicator')]";  MobileElement deliveryStatus = lastMessage.findElement (By.xpath (xpathDeliveryStatus));   I want to do the same except that I want to find the deliveryStatus variable using explicit wait.  So I want to find the deliveryStatus variable inside the lastMessage variable using  wait.until (ExpectedConditions.visibilityOfElementLocated (By.locator))   How can I do this?  I don't want to do it using one immense Xpath. Besides, I don't even know how to find the last element with the id body_bubble using Xpath, as the number of these elements is not fixed and always changing.  P.S. For example, in Python we can define WebDriverWait with an element in the constructor instead of driver:  WebDriverWait(webelement, self.timeout)  Unfortunately, it does not work in Java.
45361
What is the right way of initializing a static map? Do we need a static function that will initialize it?