Swipe/Scroll best practice with Java-Client 5

Yes I see your example.

indent preformatted text by 4 spaces@Test
    public void ChangePass(int startX, int startY, int endX, int endY, int duration) throws InterruptedException {

    WebDriverWait wait = new WebDriverWait(driver, 25);
    wait.until(ExpectedConditions.elementToBeClickable(By.id(myprofile)));

    //Click the profile icon
    driver.findElement(By.id(myprofile)).click();

    //Click the sign in button
    driver.findElement(By.id(sign)).click();

    //Enter Username
    driver.findElement(By.id(enterUsernameButton)).sendKeys("[email protected]");

    //Enter Password
    driver.findElement(By.id(enterPasswordButton)).sendKeys("Soni2017");

    //Tap the DONE button
    driver.findElement(By.id(signUpDoneButton)).click();

    wait = new WebDriverWait(driver, 15);
    wait.until(ExpectedConditions.elementToBeClickable(By.id(myprofile)));

    driver.findElement(By.id(myprofile)).click();

    driver.findElement(By.id(name)).click();

    if (!driver.findElements(By.id(editprofile)).isEmpty()) {
        Thread.sleep(1000);
        driver.findElement(By.id(editprofile)).click();

    } else {
        Thread.sleep(2000);
        driver.findElement(By.xpath(ediProfile)).click();

    }
    //Enter the code for "Edit Profile"
    //Insert a code that scrolls down to the bottom of the screen
    // Scroll down
    // X[63,904]
    // Y[365,9771

    new TouchAction((MobileDriver) driver).press(startX, startY).waitAction(Duration.ofMillis(5000)).moveTo(endX, endY).release().perform();

    //Change Password button
    driver.findElement(By.id(changePassword)).click();

After adding in your example it gave me an error saying:

java.lang.Exception: Method ChangePass should have no parameters

Hi Aleksei,

I was trying out your code. Initially it will open Settings App in IOS and execute below code. But it is not scrolling to “Battery” option.

public boolean scrollToDirection_iOS_XCTest() {
		MobileElement el = (MobileElement)aDriver.findElement(By.xpath("//*[@value='Battery']"));
		String direction = "d";
        // The main difference from swipe call with the same argument is that scroll will try to move
        // the current viewport exactly to the next/previous page (the term "page" means the content,
        // which fits into a single device screen)
        try {
            JavascriptExecutor js = (JavascriptExecutor) aDriver;
            HashMap<String, String> scrollObject = new HashMap<String, String>();
            if (direction.equals("d")) {
                scrollObject.put("direction", "down");
            } else if (direction.equals("u")) {
                scrollObject.put("direction", "up");
            } else if (direction.equals("l")) {
                scrollObject.put("direction", "left");
            } else if (direction.equals("r")) {
                scrollObject.put("direction", "right");
            }
            scrollObject.put("element", el.getId());
            scrollObject.put("toVisible", "true"); // optional but needed sometimes
            js.executeScript("mobile:scroll", scrollObject);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

@mathewkuruvila did you check that it was able find your battery element before starting scroll?

Yes. It was able to find that out.

Same issue here, anyone has found any success in it.

If somebody looking for solution for Swipe, Scroll for native apps on Android and iOS this is how I achieved

Android

  1. Based on co-ordinates technique

new TouchAction(driver).press(115, 650).waitAction(ofSeconds(1)).moveTo(115, 350).release().perform();

  1. Not sure if it’s possible to do with particular element ?

iOS

JavascriptExecutor js = (JavascriptExecutor) driver;
HashMap<String, String> swipeObject = new HashMap<String, String>();

  1. Method 1

        swipeObject.put("element", mobileElementToTakeActionUpon.getId());
        swipeObject.put("direction", "up");
        js.executeScript("mobile: swipe", swipeObject);
    

limitation - does more swipe than expected

  1. Method 2

         swipeObject.put("element", itemsViewTopRow.getId());
         swipeObject.put("direction", "down");
         swipeObject.put("toVisible", "true");
         js.executeScript("mobile: scroll", swipeObject);
    
  2. Co-ordinates based

         swipeObject.put("direction", "down"); //up for swipe
         swipeObject.put("startX", "90");
         swipeObject.put("startY", "400");
         swipeObject.put("endX", "90"); //"90");
         swipeObject.put("endY", "350"); //"200");
         swipeObject.put("duration", "2000");
         //js.executeScript("mobile: swipe", swipeObject); 
         js.executeScript("mobile: scroll", swipeObject);
    

limitation - does more swipe than expected

------- Bugs Found during this exercise -------

  1. https://github.com/appium/java-client/issues/784

  2. https://github.com/appium/java-client/issues/783

  3. https://github.com/appium/java-client/issues/785

  4. https://github.com/appium/appium/issues/9771

  5. https://github.com/appium/appium/issues/7914

I hope it helps and in case some info is missing / incorrect please add to thread.

Regards,
Vikram

2 Likes

Using your method for Android, I get the below error in appium logs when I try for a horizontal swipe right to left. Using 5.0.4 and appium 1.7.2. Any ideas?

	t.press(1000, 1500).waitAction(Duration.ofMillis(1000)).moveTo(0, 1500).release().perform();

[HTTP] --> POST /wd/hub/session/cd1cd37c-110a-43c6-a808-b6ff3eac33ac/touch/perform {“actions”:[{“action”:“press”,“options”:{“x”:1000,“y”:1500}},{“action”:“moveTo”,“options”:{“x”:0,“y”:1500}},{“action”:“release”,“options”:{}}]}
[debug] [MJSONWP] Calling AppiumDriver.performTouch() with args: [[{“action”:“press”,“options”:{“x”:1000,“y”:1500}},{“action”:“moveTo”,“options”:{“x”:0,“y”:1500}},{“action”:“release”,“options”:{}}],“cd1cd37c-110a-43c6-a808-b6ff3eac33ac”]
[debug] [AndroidBootstrap] Sending command to android: {“cmd”:“action”,“action”:“element:touchDown”,“params”:{“x”:1000,“y”:1500}}
[debug] [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got data from client: {“cmd”:“action”,“action”:“element:touchDown”,“params”:{“x”:1000,“y”:1500}}
[debug] [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command of type ACTION
[debug] [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Got command action: touchDown
[debug] [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Display bounds: [0,0][1080,1920]
[debug] [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Performing TouchDown using element? false x: 1000, y: 1500
[debug] [AndroidBootstrap] [BOOTSTRAP LOG] [debug] Returning result: {“status”:13,“value”:“Failed to execute touch event”}
[debug] [AndroidBootstrap] Received command result from bootstrap
[HTTP] <-- POST /wd/hub/session/cd1cd37c-110a-43c6-a808-b6ff3eac33ac/touch/perform 500 34 ms - 154

Best
Vince

your appium java client version is very old, can you use latest one from https://github.com/appium/java-client/releases

I believe (5.0.4) is the latest that was actually released, 6.* are in beta.

Yes, using latest stable build 5.0.4 as ochubey said. Trying this on a real Samsung S5 with 1080x1920 screen size— also same issue on Nexus 6. Also using Java JDK 8 and selenium 3.9.1. Testing on native android app.

The strange thing is it actually swiped ok one time, very very slowly (maybe over 10 seconds even though duration was set to 2 seconds). After that, it keeps erroring with subsequent runs, even with fresh restart of appium and clearing the app’s cache.

Should I submit appium bug report?

I’ve just tried this on the native Google Play Store app and it’s working as expected, so it could be an issue with the apk I am testing, as it is an older version.

Best
Vince

Thanks for clarifying, I prefer to use latest versions of client as it has quite a few bug fixes. Also it helps author to report any bugs found

Hi Vikram,

When i use the latest version of javaclient, i get the following error.

FAILED CONFIGURATION: @BeforeTest setCapabilities

java.lang.NoClassDefFoundError: org/apache/http/auth/Credentials

at com.contacts.BaseClass.setCapabilities(BaseClass.java:25)

i am using :
Selenium Version : 3.6.0

java client : 6.0.0-BETA4

TestNG :6.13.1

Appium : 1.7.2

This error is coming from the capabilities i have set in BaseClass, please find the Baseclass below :

esiredCapabilities caps = new DesiredCapabilities ();

caps.SetCapability(MobileCapabilityType.DeviceName, " ");

caps.SetCapability(MobileCapabilityType.PlatformVersion, " ");

caps.SetCapability(MobileCapabilityType.AppPackage, " ");

caps.SetCapability(MobileCapabilityType.AppActivity, " ");

We can use the following the code snippet to scroll down but please make sure you catch the exceptions.

try {
	driver.findElementByAndroidUIAutomator("new UiScrollable(new UiSelector()).scrollIntoView(text(\"\"))");
}catch(Exception e) {
	System.out.println("whatever");
}

Hi,
I tried this for Image Carousel swipe and it worked.

public boolean swipeImages()
{
try
{
WebElement pageIndicator = driver.findElement(page_indicator);
String pageString= pageIndicator.getAttribute(“value”);
int length = pageString.length();
String count_string= pageString.substring(length-2, length);
int count = Integer.parseInt(count_string);
for (int i=1; i<=count; i++){

	  JavascriptExecutor js = (JavascriptExecutor) driver;
	  HashMap<String, String> scrollObject = new HashMap<String, String>();
	  scrollObject.put("direction", "right");
	  js.executeScript("mobile: scroll", scrollObject);
	  
		   }
		   System.out.println("Swipe Successfully");
		
	}
	catch (Exception e) 
	{
		System.out.println("Image Swipe was not successful.");
		
	}

Hi, i have used the below code to Swipe / Scroll and it is working perfectly.
Code to Swipe UP
public boolean swipeFromUpToBottom()
{
try {
JavascriptExecutor js = (JavascriptExecutor) driver;
HashMap<String, String> scrollObject = new HashMap<String, String>();
scrollObject.put(“direction”, “up”);
js.executeScript(“mobile: scroll”, scrollObject);
System.out.println(“Swipe up was Successfully done.”);
}
catch (Exception e)
{
System.out.println(“swipe up was not successfull”);
}
return false;
}
Code to Swipe DOWN
public boolean swipeFromBottomToUp()
{
try {
JavascriptExecutor js = (JavascriptExecutor) driver;
HashMap<String, String> scrollObject = new HashMap<String, String>();
scrollObject.put(“direction”, “down”);
js.executeScript(“mobile: scroll”, scrollObject);
System.out.println(“Swipe down was Successfully done”);
}
catch (Exception e)
{
System.out.println(“swipe down was not successfull”);
}
return false;
}

Thanks !!

@vinitaPatil This is not working in Scroll-able Popup Menu.Do You have any Idea How to Scroll In Popup ?

@VikramVI it’s make my day but i can’t understand Code new TouchAction(driver).press(115, 650).waitAction(ofSeconds(1)).moveTo(115, 350).release().perform(); In Press you have to passed (115,650) what does That mean ? And In Move to You have to Pass (115,350) What does that mean ? How to measure Co-ordinate I don’t Know. Can You Please explain How to Measure Co-ordinate in Mobile ?

What if the list of items have dynamic text, what would be the best to click on all the items of the list using UiSelector/UiScrollable?

Here is my code for scrolling up and down.
Dimension windowSize = androidElementAndroidDriver.manage().window().getSize();
Map<String, Object> args = new HashMap<String, Object>();
args.put(“command”, “am”);
args.put(“command”, “input”);
int yearNow = Calendar.getInstance().get(Calendar.YEAR);
if (yearNow < Integer.valueOf(year)) {
args.put(“args”, Lists.newArrayList(“swipe”, windowSize.width / 2, windowSize.height / 2, windowSize.width / 2, windowSize.height / 2));

        } else {
            args.put("args", Lists.newArrayList("swipe", windowSize.width / 2, windowSize.height / 2, windowSize.width / 2, windowSize.height));
        }