# StaleElementReferenceException with UIautomator2

**URL:** <https://discuss.appium.io/t/staleelementreferenceexception-with-uiautomator2/20138>\
**Category:** Issues/Bugs\
**Created:** [December 14, 2017, 3:23pm UTC](https://discuss.appium.io/t/staleelementreferenceexception-with-uiautomator2/20138 "2017-12-14T15:23:26Z")\
**Posts on this page:** 19\
**Page:** 1

<div class="post-metadata">

**Author:** ![igal\_epshtein](https://discuss.appium.io/user_avatar/discuss.appium.io/igal_epshtein/32/5422_2.png) [@igal\_epshtein](https://discuss.appium.io/u/igal_epshtein)\
**Post date:** [December 14, 2017, 3:23pm UTC](https://discuss.appium.io/t/staleelementreferenceexception-with-uiautomator2/20138/1 "2017-12-14T15:23:26Z")

</div>

Hi Guys,

Since we’ve moved to UIautomator2 framework , “StaleElementReferenceException” makes our execution very sad 🙂

I was wondering how do you workaround this ?

The obvious solution “not to cache” the element and each time execute driver.findElementBy… is standing against the PO concept …

All our elements are Page’s properties annotated with @FindBy , if we will look for them manually each time they are needed , we are missing the entire concept…

I was wonder if there a way to make a refresh for the PageObject and by that to refresh all the cached elements ?

Thanks

---

<div class="post-metadata">

**Author:** ![Venkatesh](https://discuss.appium.io/user_avatar/discuss.appium.io/venkatesh/32/5358_2.png) [@Venkatesh](https://discuss.appium.io/u/Venkatesh)\
**Post date:** [December 14, 2017, 4:19pm UTC](https://discuss.appium.io/t/staleelementreferenceexception-with-uiautomator2/20138/2 "2017-12-14T16:19:47Z")

</div>

can you put a sample code here, to reproduce the issue.

---

<div class="post-metadata">

**Author:** ![igal\_epshtein](https://discuss.appium.io/user_avatar/discuss.appium.io/igal_epshtein/32/5422_2.png) [@igal\_epshtein](https://discuss.appium.io/u/igal_epshtein)\
**Post date:** [December 14, 2017, 4:45pm UTC](https://discuss.appium.io/t/staleelementreferenceexception-with-uiautomator2/20138/3 "2017-12-14T16:45:12Z")

</div>

```
 @AndroidFindBy(id = UIStrings.POSITION_FIXED_INCOME_TOTAL)
    private AndroidElement totalMoneyInTitle;

   public void validateTitleIsEqualSubAssets()
    {
        AbstractAppiumConnection.webDriverWait.until(new ExpectedCondition<Boolean>() {
            @Nullable
            @Override
            public Boolean apply(@Nullable WebDriver webDriver) {
                **return totalMoneyInTitle.isDisplayed();//cause to StaleException --> appium server hangs**
            }
        });
        BigDecimal title = getTotalMoneyInTheTitle();
        BigDecimal totalSubAssets = calculateTotalSumOfSubAssetsInTab();
        Assert.assertEquals("Total cash holdings is not equals total tabs",title,totalSubAssets);
    }
```

---

<div class="post-metadata">

**Author:** ![Venkatesh](https://discuss.appium.io/user_avatar/discuss.appium.io/venkatesh/32/5358_2.png) [@Venkatesh](https://discuss.appium.io/u/Venkatesh)\
**Post date:** [December 14, 2017, 5:58pm UTC](https://discuss.appium.io/t/staleelementreferenceexception-with-uiautomator2/20138/4 "2017-12-14T17:58:25Z")

</div>

I do something like below, and i don’t notice stale element exception. I would suggest make sure you are on the right page and then make a call to isDisplayed().

public void waitForWebElement(WebElement weblement){  
try {  
new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOf(weblement));  
}  
catch(Exception ex){

```
        System.out.println("WebElement "+weblement.toString() +" not found");
    }

}
```

---

<div class="post-metadata">

**Author:** ![Aleksei](https://discuss.appium.io/user_avatar/discuss.appium.io/aleksei/32/6267_2.png) [@Aleksei](https://discuss.appium.io/u/Aleksei)\
**Post date:** [December 14, 2017, 8:44pm UTC](https://discuss.appium.io/t/staleelementreferenceexception-with-uiautomator2/20138/5 "2017-12-14T20:44:36Z")

</div>

@igal_epshtein i used similar to @Venkatesh without issues. BUT this is for WEB!

```auto
    public Boolean waitElementForVisibility(List<WebElement> el) {
        return waitElementForVisibility(el, 0, 10);
    }

    public Boolean waitElementForVisibility(List<WebElement> el, int num) {
        return waitElementForVisibility(el, num, 10);
    }

    public Boolean waitElementForVisibility(List<WebElement> el, int num, int seconds) {
        WebDriverWait wait = new WebDriverWait(driver, seconds);
        try {
            WebElement element = wait.until(
                    ExpectedConditions.visibilityOf(el.get(num)));
            if (element.isDisplayed())
                return true;
            else
                return false;
        } catch (Exception e) {
            return false;
        }
    }

```

for Android NATIVE you should use directly:

```auto
    @AndroidFindBy(id = "title")
    private List<AndroidElement> dialogTitle;

    public String getDialogTitle() {
        if (dialogTitle.isEmpty())
            return null;
        else
            return dialogTitle.get(0).getText();
    }

```

where timeout for dialogTitle is set in page init:

```auto
PageFactory.initElements(new AppiumFieldDecorator(driver, DEFAULT_WAIT_TIME, SECONDS), this);

```

---

<div class="post-metadata">

**Author:** ![igal\_epshtein](https://discuss.appium.io/user_avatar/discuss.appium.io/igal_epshtein/32/5422_2.png) [@igal\_epshtein](https://discuss.appium.io/u/igal_epshtein)\
**Post date:** [December 20, 2017, 1:21pm UTC](https://discuss.appium.io/t/staleelementreferenceexception-with-uiautomator2/20138/6 "2017-12-20T13:21:26Z")

</div>

but this one doesn’t answer the stalerefernce issue …

The stalereference occurs once the application view is being destroyed and created once again , then the page’s object is pointing to “old” view element which actually doesn’t exist anymore …

I was wonder if there is a way to “refresh” the page object , and to initialise it with new view elements

---

<div class="post-metadata">

**Author:** ![Aleksei](https://discuss.appium.io/user_avatar/discuss.appium.io/aleksei/32/6267_2.png) [@Aleksei](https://discuss.appium.io/u/Aleksei)\
**Post date:** [December 20, 2017, 3:02pm UTC](https://discuss.appium.io/t/staleelementreferenceexception-with-uiautomator2/20138/7 "2017-12-20T15:02:23Z")

</div>

@igal_epshtein page object does not point to anywhere. element starts finding whenever you call it find not at the moment of page object init.

---

<div class="post-metadata">

**Author:** ![igal\_epshtein](https://discuss.appium.io/user_avatar/discuss.appium.io/igal_epshtein/32/5422_2.png) [@igal\_epshtein](https://discuss.appium.io/u/igal_epshtein)\
**Post date:** [December 20, 2017, 3:24pm UTC](https://discuss.appium.io/t/staleelementreferenceexception-with-uiautomator2/20138/8 "2017-12-20T15:24:20Z")

</div>

> [@Aleksei](#):
>
> age object does not point to anywhere. element starts finding whenever you call it find not at the moment of page object init.

once you’ve used the page object , it has a reference to view’s object , in case and the last one was recreated you get Stale exception…

---

<div class="post-metadata">

**Author:** ![Aleksei](https://discuss.appium.io/user_avatar/discuss.appium.io/aleksei/32/6267_2.png) [@Aleksei](https://discuss.appium.io/u/Aleksei)\
**Post date:** [December 21, 2017, 7:37am UTC](https://discuss.appium.io/t/staleelementreferenceexception-with-uiautomator2/20138/9 "2017-12-21T07:37:59Z")

</div>

@igal_epshtein you are wrong 😀 . it has reference to object but not elements mentioned in object. Thus whenever e.g. you try to click in page object by element each time it will start looking for element from zero. There is strategy to override this. But you need enable cache strategy which is other story.

---

<div class="post-metadata">

**Author:** ![igal\_epshtein](https://discuss.appium.io/user_avatar/discuss.appium.io/igal_epshtein/32/5422_2.png) [@igal\_epshtein](https://discuss.appium.io/u/igal_epshtein)\
**Post date:** [December 21, 2017, 8:01am UTC](https://discuss.appium.io/t/staleelementreferenceexception-with-uiautomator2/20138/10 "2017-12-21T08:01:16Z")

</div>

@Aleksei not sure you are right 🙂

I’m getting the stale exception on the same line of code always after the view was recreated (some application’s flow)

---

<div class="post-metadata">

**Author:** ![Aleksei](https://discuss.appium.io/user_avatar/discuss.appium.io/aleksei/32/6267_2.png) [@Aleksei](https://discuss.appium.io/u/Aleksei)\
**Post date:** [December 21, 2017, 8:46am UTC](https://discuss.appium.io/t/staleelementreferenceexception-with-uiautomator2/20138/11 "2017-12-21T08:46:24Z")

</div>

@igal_epshtein try to see appium logs with following test:

1. do click to simple text file several times

Result: with every click first command search for element -\> then click to element by found element ID.

anyway suggestion: do clicker function and point to it EVERY click in page objects. in clicker when you see stale error do e.g. pause for 100ms and retry click. Limit this e.g. to 5 tries to avoid loop. good luck 🙂

---

<div class="post-metadata">

**Author:** ![igal\_epshtein](https://discuss.appium.io/user_avatar/discuss.appium.io/igal_epshtein/32/5422_2.png) [@igal\_epshtein](https://discuss.appium.io/u/igal_epshtein)\
**Post date:** [December 21, 2017, 9:05am UTC](https://discuss.appium.io/t/staleelementreferenceexception-with-uiautomator2/20138/12 "2017-12-21T09:05:27Z")

</div>

@Aleksei - this is not happens with click only , but every operation on the page (isDisplayed , setText…)

Apium guys should fix this issue for UIAutomator2 package 😉

---

<div class="post-metadata">

**Author:** ![Aleksei](https://discuss.appium.io/user_avatar/discuss.appium.io/aleksei/32/6267_2.png) [@Aleksei](https://discuss.appium.io/u/Aleksei)\
**Post date:** [December 21, 2017, 9:50am UTC](https://discuss.appium.io/t/staleelementreferenceexception-with-uiautomator2/20138/13 "2017-12-21T09:50:25Z")

</div>

@igal_epshtein wow something new for me 🙂

---

<div class="post-metadata">

**Author:** ![sheikh\_jebran](https://discuss.appium.io/user_avatar/discuss.appium.io/sheikh_jebran/32/5778_2.png) [@sheikh\_jebran](https://discuss.appium.io/u/sheikh_jebran)\
**Post date:** [May 19, 2019, 2:05am UTC](https://discuss.appium.io/t/staleelementreferenceexception-with-uiautomator2/20138/14 "2019-05-19T02:05:46Z")

</div>

Hi ,  
Am also facing the same issue for UIAutomator2

---

<div class="post-metadata">

**Author:** ![aturfer](https://discuss.appium.io/letter_avatar_proxy/v4/letter/a/e19b73/32.png) [@aturfer](https://discuss.appium.io/u/aturfer)\
**Post date:** [August 14, 2019, 3:56pm UTC](https://discuss.appium.io/t/staleelementreferenceexception-with-uiautomator2/20138/15 "2019-08-14T15:56:36Z")

</div>

I too am facing this issue. If I put the thread to sleep for a second before accessing someElement.isDisplayed(), then I do not get the StaleElementReferenceException, but this dramatically increases test execution time for large tests (it’s also very ugly, I was told not to use sleeps).

There must be another way… 🤔

---

<div class="post-metadata">

**Author:** ![MihaiDRus](https://discuss.appium.io/letter_avatar_proxy/v4/letter/m/da6949/32.png) [@MihaiDRus](https://discuss.appium.io/u/MihaiDRus)\
**Post date:** [January 8, 2020, 8:30am UTC](https://discuss.appium.io/t/staleelementreferenceexception-with-uiautomator2/20138/16 "2020-01-08T08:30:32Z")

</div>

Hello guys, I am still facing this issue, any updates?

---

<div class="post-metadata">

**Author:** ![Seggev](https://discuss.appium.io/user_avatar/discuss.appium.io/seggev/32/8122_2.png) [@Seggev](https://discuss.appium.io/u/Seggev)\
**Post date:** [September 30, 2020, 7:28pm UTC](https://discuss.appium.io/t/staleelementreferenceexception-with-uiautomator2/20138/17 "2020-09-30T19:28:34Z")

</div>

I think i have solved it.  
My problem was that the element was showing on screen but appium couldn’t find it.  
As funny as it may seem, resetting my TouchAction object did the work.  
I just added at the start of the function:  
touchAction = new TouchAction(driver);  
so if you are using a TouchAction object, try resetting it.  
I am using 2 Android drivers simultaneously so appium was recognising the other device’s page.

---

<div class="post-metadata">

**Author:** ![ihorppp](https://discuss.appium.io/user_avatar/discuss.appium.io/ihorppp/32/7765_2.png) [@ihorppp](https://discuss.appium.io/u/ihorppp)\
**Post date:** [October 22, 2020, 11:01am UTC](https://discuss.appium.io/t/staleelementreferenceexception-with-uiautomator2/20138/18 "2020-10-22T11:01:57Z")

</div>

Hi guys,

I’m using Java Appium 7.2.0, Appium 1.17.0 and PageFactory approach and get StaleElementReferenceException after element is found.  
After reviewing video of the automation session it does seem like Android view is being recreated in an instant. Is there any possible solution how to handle such issue?

Here are some Appium logs:

```
2020-10-21 21:43:41:720 - [debug] [MJSONWP (7130dace)] Calling AppiumDriver.findElement() with args: ["accessibility id","phoneNumberField","7130dace-87d0-4e24-be9e-46cbb5c97af6"]
2020-10-21 21:43:41:721 - [debug] [BaseDriver] Valid locator strategies for this request: xpath, id, class name, accessibility id, -android uiautomator
2020-10-21 21:43:41:721 - [debug] [BaseDriver] Waiting up to 0 ms for condition
2020-10-21 21:43:41:722 - [debug] [WD Proxy] Matched '/element' to command name 'findElement'
2020-10-21 21:43:41:722 - [debug] [WD Proxy] Proxying [POST /element] to [POST http://127.0.0.1:8202/wd/hub/session/828dacc9-510e-4030-af54-1d10f296ea6c/element] with body: {"strategy":"accessibility id","selector":"phoneNumberField","context":"","multiple":false}
2020-10-21 21:43:42:172 - [debug] [WD Proxy] Got response with status 200: {"sessionId":"828dacc9-510e-4030-af54-1d10f296ea6c","value":{"ELEMENT":"b86f31c5-e703-4d1c-a984-89256ea60666","element-6066-11e4-a52e-4f735466cecf":"b86f31c5-e703-4d1c-a984-89256ea60666"}}
2020-10-21 21:43:42:173 - [debug] [MJSONWP (7130dace)] Responding to client with driver.findElement() result: {"element-6066-11e4-a52e-4f735466cecf":"b86f31c5-e703-4d1c-a984-89256ea60666","ELEMENT":"b86f31c5-e703-4d1c-a984-89256ea60666"}
2020-10-21 21:43:42:174 - [HTTP] <-- POST /wd/hub/session/7130dace-87d0-4e24-be9e-46cbb5c97af6/element 200 454 ms - 199
2020-10-21 21:43:42:174 - [HTTP] 
2020-10-21 21:43:42:448 - [HTTP] --> GET /wd/hub/session/7130dace-87d0-4e24-be9e-46cbb5c97af6/element/b86f31c5-e703-4d1c-a984-89256ea60666/displayed
2020-10-21 21:43:42:448 - [HTTP] {}
2020-10-21 21:43:42:449 - [debug] [MJSONWP (7130dace)] Calling AppiumDriver.elementDisplayed() with args: ["b86f31c5-e703-4d1c-a984-89256ea60666","7130dace-87d0-4e24-be9e-46cbb5c97af6"]
2020-10-21 21:43:42:452 - [debug] [WD Proxy] Matched '/element/b86f31c5-e703-4d1c-a984-89256ea60666/attribute/displayed' to command name 'getAttribute'
2020-10-21 21:43:42:452 - [debug] [WD Proxy] Proxying [GET /element/b86f31c5-e703-4d1c-a984-89256ea60666/attribute/displayed] to [GET http://127.0.0.1:8202/wd/hub/session/828dacc9-510e-4030-af54-1d10f296ea6c/element/b86f31c5-e703-4d1c-a984-89256ea60666/attribute/displayed] with body: {}
2020-10-21 21:43:42:747 - [WD Proxy] Got response with status 404: {"sessionId":"828dacc9-510e-4030-af54-1d10f296ea6c","value":{"error":"stale element reference","message":"The element 'By.accessibilityId: phoneNumberField' does not exist in DOM anymore","stacktrace":"
io.appium.uiautomator2.common.exceptions.StaleElementReferenceException: The element 'By.accessibilityId: phoneNumberField' does not exist in DOM anymore
io.appium.uiautomator2.model.KnownElements.restoreCachedElement(KnownElements.java:103)
io.appium.uiautomator2.model.KnownElements.getElementFromCache(KnownElements.java:122)
io.appium.uiautomator2.handler.GetElementAttribute.safeHandle(GetElementAttribute.java:26)
io.appium.uiautomator2.handler.request.SafeRequestHandler.handle(SafeRequestHandler.java:38)
io.appium.uiautomator2.server.AppiumServlet.handleRequest(AppiumServlet.java:252)
io.appium.uiautomator2.server.AppiumServlet.handleHttpRequest(AppiumServlet.java:242)
io.appium.uiautomator2.http.ServerHandler.channelRead(ServerHandler.java:51)\n\tat io.netty.chan...
2020-10-21 21:43:42:748 - [debug] [W3C] Matched W3C error code 'stale element reference' to StaleElementReferenceError
```

---

<div class="post-metadata">

**Author:** ![vzenzo](https://discuss.appium.io/user_avatar/discuss.appium.io/vzenzo/32/7067_2.png) [@vzenzo](https://discuss.appium.io/u/vzenzo)\
**Post date:** [January 18, 2021, 1:46pm UTC](https://discuss.appium.io/t/staleelementreferenceexception-with-uiautomator2/20138/19 "2021-01-18T13:46:06Z")

</div>

wait is good solution but unfortunately doesn’t work always
