Scrolling to element in android app using java

The following code works fine for me.

public WebElement scrollToAnElementByText(AppiumDriver<WebElement> driver, String text) {
        return driver.findElement(MobileBy.AndroidUIAutomator("new UiScrollable(new UiSelector())" +
                ".scrollIntoView(new UiSelector().text(\"" + text + "\"));"));
}
2 Likes

Thank you Anto_Rodrigo

This got worked for me.

I am searching for year from drop down, and it is present at the end of that drop down but its not visible whenever I open that drop down. So I used function that you have mentioned above and it got worked for me very well.

1 Like

Sounds good :slight_smile: @Mayuresh92

do you know how to scroll horizontal? if yes please let me know codes.

Hi @Aleksei
i am facing java.lang.NullPointerException :

This is my code
public WebElement scrollToAnElementByText(AndroidDriver driver1, String text)
{
return Adriver.findElement(MobileBy.AndroidUIAutomator
(“new UiScrollable(new UiSelector())” +""
+ “.scrollIntoView(new UiSelector().text(”" + text + “”));"));
}

JavascriptExecutor js = (JavascriptExecutor) Adriver;

// HashMap<String, String> scrollObject = new HashMap<String, String>();

// scrollObject.put(“direction”, “down”);

// js.executeScript(“mobile: scroll”, scrollObject);

Can you please help me to resolve the issue!

public WebElement scrollToAnElementByText(AndroidDriver driver1, String text)
{
return Adriver.findElement(MobileBy.AndroidUIAutomator

see driver1 vs Adriver

19%20AM|226x499

in the test page
Pray4MeRequestPage p1 = new Pray4MeRequestPage(driver1);
p1.scrollToAnElementByText(driver1, “Submit”);

in the find element page, in this page i have declared & initialised Android driver as Adriver
public WebElement scrollToAnElementByText(AndroidDriver Adriver, String text)
{
return Adriver.findElement(MobileBy.AndroidUIAutomator
(“new UiScrollable(new UiSelector())” +""
+ “.scrollIntoView(new UiSelector().text(”" + text + “”));"));
}
i am using POM frame work,
there is resource id, i have only text to find element, initially when the page opens Submit button will be hidden i need to scroll to submit button.
Can you please help me

Thanks, it works for me. Tried scroll down with native app, android

Thank for your sharing

I share my code for who needs

public static void scrollToText(AndroidDriver<MobileElement> driver, String text) {
	MobileElement el = (MobileElement) driver.findElementByAndroidUIAutomator("new UiScrollable("
			+ "new UiSelector().scrollable(true)).scrollIntoView(" + "new UiSelector().text(\"" + text + "\"));");
}

public static void scrollToId(AndroidDriver<MobileElement> driver, String id) {
	MobileElement el = (MobileElement) driver.findElementByAndroidUIAutomator(
			"new UiScrollable(" + "new UiSelector().scrollable(true)).scrollIntoView("
					+ "new UiSelector().resourceIdMatches(\"" + id + "\"));");
}```

Hello Aleksei
I tried with this code but it’s throwing error

driver.findElement(MobileBy.AndroidUIAutomator(“new UiSelector().resourceIdMatches(”.*id / com.barclays.absa.banking.uat:id/floatingActionButton"]")"));

-> replace to:

driver.findElement(MobileBy.AndroidUIAutomator(“new UiSelector().resourceIdMatches(”.*id/floatingActionButton"]")"));

Hi @Aleksei,

Good day, I tried also the code you have provided from the previous comment and wondering how I can select/click the element not visible on the panel of my mobile android device. Provided below are my code and new UiSelector is scrolling and working on some app but for no apparent reason it does not works on the app our dev is currently creating. Details are given below.
Kindly help as I am still trying to learn Appium. Thank you and good day.

appium --1.16.0
java version “1.8.0_231”

code:
public static void openKYC() throws Exception {

	DesiredCapabilities cap = new DesiredCapabilities();
	
	cap.setCapability("deviceName", "CAM-L21");
	cap.setCapability("udid", "LHTDU17601000834");
	cap.setCapability("platformName", "Android");
	cap.setCapability("platformVersion", "6.0");
	cap.setCapability("automationName", "UiAutomator1");
	cap.setCapability("appPackage", "com.cimb.ekyc");  
	cap.setCapability("appActivity", "com.cimb.ekyc.MainActivity");
	
	URL url = new URL("http://127.0.0.1:4723/wd/hub");
	
	driver = new AndroidDriver<MobileElement>(url, cap);
	driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
	
	System.out.println("KYC Application Test Started...");		
	
	driver.findElement(By.className("android.widget.Button")).click();

	driver.findElementByXPath("//android.view.View[@text='E-i navigation icon EcoSave Savings Account-i Online, paperless, and environmentally friendly']").click();
	

	((FindsByAndroidUIAutomator<MobileElement>) driver).findElementByAndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().textContains(\"Green Environmental Activities\").instance(0))");
	
   }

}

On Appium server: there is an error (UiObjectNotFoundException) as per screenshot below:

Appium UI Element Inspector:

  1. why? change to:
capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.ANDROID_UIAUTOMATOR2);
  1. can you pls move to newer android at least 9?
  2. try replace “new UiSelector().textContains(“Green Environmental Activities”).instance(0)” -> “new UiSelector().textContains(“Green Environmental Activities”)”
  3. see in page source tree “android.widgetListView”. if it has any resource id add it to here:
new UiSelector().scrollable(true).resourceIdMatches(".*id/your_id")

Hi @Aleksei

Here are my response:

  1. Only UiAutomator1 is running for mobile device hence if I use UiAutomator2 it will have error.
  2. Our test mobile test device is using Android 6 system.
  3. Replaced the code as suggested by you.
  4. I have attached the Appium Source tree, there is no resource id on the widget list, only on the frame layout itself as shown below.

Thank you, Aleksei

Java Code:
public static void openKYC() throws Exception {

	DesiredCapabilities cap = new DesiredCapabilities();
	
	cap.setCapability("deviceName", "CAM-L21");
	cap.setCapability("udid", "LHTDU17601000834");
	cap.setCapability("platformName", "Android");
	cap.setCapability("platformVersion", "6.0");
	cap.setCapability("automationName", "UiAutomator1");
	cap.setCapability("appPackage", "com.cimb.ekyc");  
	cap.setCapability("appActivity", "com.cimb.ekyc.MainActivity");
	
	URL url = new URL("http://127.0.0.1:4723/wd/hub");

// driver = new AppiumDriver(url, cap);
driver = new AndroidDriver(url, cap);
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

	System.out.println("KYC Application Test Started...");		
	
	Thread.sleep(7000);
	driver.findElement(By.className("android.widget.Button")).click();
	Thread.sleep(5000);
	driver.findElementByXPath("//android.view.View[@text='E navigation icon EcoSave Savings Account-i Online, paperless, and environmentally friendly']").click();

	 
	((FindsByAndroidUIAutomator<MobileElement>) driver).findElementByAndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).**resourceIdMatches(\"android:id/content\")).scrollIntoView(new UiSelector().textContains(\"Green Environmental Activities\"))");**

Appium Server log:

wow. this is web view! which may work tricky. better switch context to web and use “click()” on element as with usual web. do not use uiSelector. imagine you are automating web.

After you switch to webView you will see ALL screen elements even outside visible area.

hi @Aleksei,

Previously, I was automating on our angular web using a Protractor but our team creates another app using PWA for a mobile wherein the customer can select accessing thru web (automation completes) and thru an app (PWA, ongoing automation) in mobile but experiencing problem scrolling down to certain elements.

Can you help elaborate further as I am not getting you. You mean I go use Protractor again? or should I use Aappium for the mobile app testing…Kindly help. thank you, Aleksei.

no. same appium. but when you switch into webView now you can run commands just like on web.
e.g. el.click().

to start:

  1. on this screen switch context to web -> Unable to identify the webelement in Android6.x versions
  2. after successful switch execute:
Document doc = Jsoup.parseBodyFragment(driver.findElement(By.cssSelector("body")).getAttribute("outerHTML"));
System.out.println("\n" + doc.toString());

you will see page structure same is on web.
3. now found element you need and just click on it:

driver.findElement(By.cssSelector("your_css_selector").click();
1 Like

Hi @Aleksei,

  1. I tried putting the code as shown below, I paste the code you have provided below after I click the open account and loads to a web view as shown below…Do I need to change something here on the given code? Thanks

         System.out.println("KYC Application Test Started...");		
     
     Thread.sleep(7000);
     driver.findElement(By.className("android.widget.Button")).click();		
     
          try {
     	switchToWebView();
     } catch (Exception exp) {
     	// TODO Auto-generated catch block
     	
     	System.out.println(exp.getCause());
     	System.out.println(exp.getMessage());
     	exp.printStackTrace();
     	
     }
     				
     Thread.sleep(5000);
     driver.findElementByXPath("//android.view.View[@text='E navigation icon EcoSave Savings Account-i Online, paperless, and environmentally friendly']").click();
  1. after click on ‘open account’ webView will not appear immediately. so put simple sleep here for a while and fix it later more smarter.
  2. switchToWebView(); better put try-catch inside “switchToWebView”.
  3. now after switch in web no more “android.view.View”. use css.