Get index attribute of element

I have an issue where I need to get the index attribute of a parent node based on its child. The situation is a chat screen where I need to get the chat buble’s index based on the message content.

What I have so far is this:

	public String chatBubbleIndexByMessage(String message) {
		String xpath = "//*[@resource-id='com.chat:id/msg_content' and @text='Message #1']/../../../..";
		Locator bubbleIndexLocator = Locator.xpath(xpath);
		String bubbleIndex = driver.getElement(bubbleIndexLocator).getAttribute("index");
		return bubbleIndex;
	}

Where I find the text of the message (“Message #1”) and go up 4 parents to get to the chat bubble’s node (where the index attribute is). Problem is that the getAttribute method has a list of supported attributes, and it doesn’t include the index one.

Is there some other way to get that index?

index is not exposed because it’s an internal field.

Try to look at this problem from the other side. Let say the test wants to verify that a message with text ‘blabla’ is the third one along other messages. Then the fact the following xpath is found would confirm that:

//view[@id="parentView"]/view[@id="message"][3]

Thanks for the reply. I adapted your idea to the method and it now iterates over all the chat bubbles checking if the message parameter is equal to the bubble content:

	public int chatBubbleIndexByMessage(String message) {
		int chatBubbleIndex = 1;
		while (chatBubble(chatBubbleIndex).exists()) {
			if (chatBubble(chatBubbleIndex).messageContent().getText().equals(message)) {
				return chatBubbleIndex;
			}
			chatBubbleIndex++;
		}
		return -1;
	}

It takes a few seconds to execute, but gets the work done.

It takes a few seconds to execute, but gets the work done.

This is suboptimal. Try to do as little requests to the server as possible. The code below could be reduced to a single locator usage:

private static final Function<By, String> bubbleByContent = 
          content -> By.xpath(String.format("//view[@id=\"container\"]/view[@id=\"message\" and @text=\"%s\"]/preceding-sibling::view[@id=\"message\"]", content));

public int chatBubbleIndexByMessage(String message) {
     var siblingsCount = driver.findElements(bubbleByContent.apply(message)).size();
     return siblingsCount > 0 ? siblingsCount + 1 : -1;
}