Rather than storing references to elements, it is important to locate and interact with them dynamically to avoid the StaleElementReferenceException. To do this, one must use a combination of explicit waits and polling to locate elements. Then, the element must be interacted with immediately after locating it to avoid the exception. This can be done by using the appropriate methods available in the Selenium WebDriver API.

Code example one:
Try to refresh the page before send the keys.

driver.navigate().refresh();
driver.findElement(By.id("APjFqb")).sendKeys("1234567");

Code example two:
Use try catch and in catch block try to initiate a variable.

  try {
driver.get("https://www.google.com");
driver.findElement(By.id("APjFqb")).sendKeys("1234567");
    System.out.println("method f id:"+Thread.currentThread().getId()+" n:"+n+" s:"+s);
}catch(StaleElementReferenceException e) {
 	driver.findElement(By.id("APjFqb")).sendKeys("1234567");
}

Support On Demand!

                                         
QA Automation