Xpath searching from the context of another element is not working as expected

Environment
Appium 1.5.3
Android

Background
I have a scenario where I need to determine on run time if an element has a child element of a certain type (android.widget.TextView) and then get its text.

Problem
When the test runs, appium successfully detects if the child element exists BUT when I try to get its text (when it exists), it returns the text of first android.widget.TextView element from TOP of the page.

Code

WebElement container = driver.findElementByXPath("//android.support.v7.widget.LinearLayoutCompat");

List<WebElement> allTextViewsInContainer = container.findElements(By.xpath(".//android.widget.TextView"));
if(allTextViewsInContainer.size() > 0)
{
	for (WebElement textView : allTextViewsInContainer)
	{
		String text = textView.getText(); //Appium gets the text of first 'android.widget.TextView' on the page and goes downwards untils the loop ends.
     }
}

Note
And it works fine when I use following code (therefore there is certainly a problem with Xpath searching from the context of another element)

List<WebElement> allTextViewsInContainer = driver.findElementsByXPath("//android.support.v7.widget.LinearLayoutCompat//android.widget.TextView");
if(allTextViewsInContainer.size() > 0)
{
	for (WebElement textView : allTextViewsInContainer)
	{
		String text = textView.getText();
     }
}

Has anyone seen this issue before?
Thanks.

Yes, it’s an Xpath bug with Appium. I have definitely come across this before.

The bug occurs because Appium is currently unable to associate a given WebElement with a given View in Android. There is also no API or framework available within Android for resolving Xpath queries against the Android view hierarchy. Thus, context-specific Xpath queries can not be resolved. Currently, it looks like they context-specific queries simply resolve from the root of the view hierarchy (unintuitive, yes?).

I think there might be a GitHub issue open for this somewhere on the Appium server project. I’m too lazy to check myself. :stuck_out_tongue:

@afwang Thanks for confirming that.

I tried searching for the bug in GitHub but couldn’t find it.
Logged a new bug - https://github.com/appium/appium/issues/6700

1 Like