How to tell if Android checkbox is checked or not

I’m new to Appium and I’m working on a test case for a native Android app. I need to determine if a checkbox is already checked or not. Here’s the code to find the checkbox.

AndroidElement clipBoardGetCheckBox = driver.findElementByXPath("//android.widget.LinearLayout[@index='1']/android.widget.LinearLayout[@index='2']/android.widget.CheckBox[@index='0']");

I’ve tried the following:

clipBoardGetCheckBox.getAttribute("checked")
clipBoardGetCheckBox.isEnabled()
clipBoardGetCheckBox.isSelected()

None of these seem to reliably tell me when the checkbox is both checked and unchecked. Am I doing something wrong or is there a better way to determine the state of a checkbox?

We use the boolean value returned by “checked” and it’s reliable for us. Sorry I can’t offer any more than that. Are you certain your xpath is pointing at the right element?

Thanks for the info. I’m not sure why yet but you’re right in suggesting that my xpath isn’t finding the right checkbox. This particular UI has three checkboxes and it seems that my xpath is finding the first one when the one I want is the second one. Also, thanks for confirming that the “checked” value is working properly for you.

I had the same issue and finally came with the below solution :-

You shall try using the getAttribute property of a WebElement as follows-
List chkBx = driver.findElements(By.className(“android.widget.CheckBox”));
String a=chkBx.get(0).getAttribute(“checked”);
System.out.println(“Check box is” + a);

It will return true or false as String .

4 Likes

thank. i completed and success

1 Like

Late to reply, but figure I’d share what I ran into…
For me, it was actually a Java issue. Specifically, I was using the “==” operator to compare 2 Strings (which in Java, compares their reference, NOT their value!). The below is what worked for me…

MobileElement checkbox = (MobileElement) driver.findElementByXPath(“some xpath”);
if (checkbox.getAttribute(“checked”).equals(“false”))