How to deal with datepicker in Appium Android - java

My android application is using datepicker but i am not able to select date through datepicker. I used following code in application for datepicker but it does not work.
List<WebElement> pick = driver.findElements(By.className("android.widget.EditText"));
pick.get(0).sendKeys("21");
pick.get(1).sendKeys("Mar");
pick.get(2).sendKeys("1989");

Swipe method will help you to scroll calendar dates , Make sure that you have added Java-client JARs to your project then only swipe method will support.
Example :
First click on your calendar icon and then use following code :
Thread.sleep(5000);
for(int y=0;y<3;y++)
{
driver.swipe(350,511,350,577,0);
}
Swipe Syntax :
driver.swipe(startx, starty, endx, endy, duration);
Note : Above in code I have used sample co-ordinates so you change it according to your need. You can get exact co-ordinates from bound values of that date picker.
I have used loop in above code as I want to swipe 3 times , so it is something like if current date is 1st may then it will swipe till 4th may.
you can modify loop as per your need.

I have used Xpath to perform Datepicker action & it is working properly.
driver.findElement(By.xpath("//android.widget.NumberPicker[#index='0']")).sendKeys("Jan");
driver.findElement(By.xpath("//android.widget.NumberPicker[#index='1']")).sendKeys("24");
driver.findElement(By.xpath("//android.widget.NumberPicker[#index='2']")).sendKeys("1987");

For all the user who are still finding the way to select date can use the below code. I am using this code and working perfectly for me. It will work for calendar attached.
do {
WebElement source = driver.findElement(By.xpath("//android.view.View[#instance='0']"));
WebElement destination = driver.findElement(By.xpath("//android.view.View[#instance='22']"));
TouchAction action = new TouchAction((PerformsTouchActions)driver);
System.out.println("Dragging item");
action.longPress(source).moveTo(destination).release().perform();
boolean bul = driver.findElementsByXPath("//android.view.View[#content-desc='24 January 2018']").isEmpty();
} while(bul!=false);
driver.findElementByAccessibilityId("24 January 2018").click();
NOTE: I used drag and drop touch action to scroll and this will scroll uptill given date is not found. I just selected same years previous month date. You can use same touch action to select desired year.

I wanted to do the same thing, but for a "calendar" mode DatePicker instead of the "spinner" mode. This is my solution, which has been working fine for me.
from datetime import datetime
datePickerYearTextViewXpath = "//android.widget.TextView[#resource-id='android:id/date_picker_header_year']"
# initialize your appium driver here
driver = getAppiumDriver()
# define some screen dimensions
screenSize = driver.get_window_size()
halfScreenWidth = screenSize['width'] // 2
halfScreenHeight = screenSize['height'] // 2
def getDatePickerCurrentDate(driver):
yearTextView = driver.find_element_by_xpath(datePickerYearTextViewXpath)
yearString = yearTextView.text
dateTextView = driver.find_element_by_xpath("//android.widget.TextView[#resource-id='android:id/date_picker_header_date']")
dateString = dateTextView.text
fullDateString = '{}, {}'.format(dateString, yearString)
currentDate = datetime.strptime(fullDateString, '%a, %b %d, %Y').date()
return currentDate
def setDatePickerDate(driver, targetDate):
# driver is an appium driver
# targetDate must be a datetime.date, not a datetime
currentDate = getDatePickerCurrentDate(driver)
if targetDate.year != currentDate.year:
yearTextView = driver.find_element_by_xpath(datePickerYearTextViewXpath)
yearTextView.click()
# you may need to adjust the following numbers
# depending on your screen size
swipeAmountPerYear = 49
yearsPerScreen = 8
swipeDuration = 400
yearOffset = targetDate.year - currentDate.year
# if target year is older, swipe up (negative)
swipeDirection = -1 if yearOffset < 0 else 1
swipeVector = yearsPerScreen * swipeAmountPerYear * swipeDirection
while True:
elements = driver.find_elements_by_xpath("//android.widget.TextView[#resource-id='android:id/text1']".format(targetDate.year))
found = False
for element in elements:
if element.text == str(targetDate.year):
element.click()
found = True
break
if found:
break
else:
driver.swipe(halfScreenWidth, halfScreenHeight, halfScreenWidth, halfScreenHeight - swipeVector, swipeDuration)
currentDate = getDatePickerCurrentDate(driver)
if targetDate.month != currentDate.month:
monthOffset = targetDate.month - currentDate.month
prevOrNext = 'prev' if monthOffset < 0 else 'next'
prevOrNextButtonXpath = "//android.widget.ImageButton[#resource-id='android:id/{}']".format(prevOrNext)
for i in range(abs(monthOffset)):
driver.find_element_by_xpath(prevOrNextButtonXpath).click()
targetDateContentDescription = targetDate.strftime('%d %B %Y')
driver.find_element_by_xpath("//android.view.View[#resource-id='android:id/month_view']/android.view.View[#content-desc='{}']".format(targetDateContentDescription)).click()
currentDate = getDatePickerCurrentDate(driver)
if currentDate != targetDate:
raise ValueError('Unable to set date picker({}) to target date({})!'.format(currentDate, targetDate))

Check if this helps
driver.FindElement(By.Id("com.eos.eos_du_su:id/ed_manufdate")).Click();
((AndroidElement)(driver.FindElement(By.XPath("//android.widget.NumberPicker[#index='0']//android.widget.Button[#index=0]")))).Tap(1, 2);
((AndroidElement)(driver.FindElement(By.XPath("//android.widget.NumberPicker[#index='1']//android.widget.Button[#index=0]")))).Tap(1, 2);
((AndroidElement)(driver.FindElement(By.XPath("//android.widget.NumberPicker[#index='2']//android.widget.Button[#index=0]")))).Tap(1, 2);
driver.FindElement(By.Id("android:id/button1")).Click();

Related

Vaadin pie chart label formatter not working

I have a chart in Vaadin 8 with the following formatter for y axis labels:
chart.getConfiguration().getyAxis().getLabels()
.setFormatter("function() { return this.point.name + ' sample'; }");
I can't seem to get it to work correctly, as the chart always displays only the point.name part and not the ' sample' part. I did the same for the tooltip where it works:
chart.getConfiguration().getTooltip()
.setFormatter("function() { return this.point.name + ' sample'; }");
Screenshot for confirmation:
After quite some time I found the answer, I had to set the label formatting function in the PlotOptionsPie object:
PlotOptionsPie plot = new PlotOptionsPie();
plot.setInnerSize("60%"); // hollow inside -> "donut" chart
plot.getDataLabels().setFormatter("function() { return this.point.name + ' sample'; }");
chart.getConfiguration().setPlotOptions(plot);
The result:

Unable to click on EditText field which is not in focus

I have a situation like I am automating a native app using Appium(1.3.7) and Selenium webdriver (2.44) in that I want to enter the Date of birth field, when I am clicking on Date of birth field, it will pop up a window to enter the date of birth details, that window is not in focus and appium is failing to enter the details on the window as it is not able to recognize here I am not able to attach the screenshot.
Please help me how to get in to focus and enter the Date of birth details..
Using Google I tried a lot of methods like:
Method : 1
List<WebElement> Listed= dr.findElementsByClassName("android.widget.EditText");
for(int i=0; i <=Listed.size()-1;i++){
System.out.println("EditText Number="+i);
Listed.get(i).sendKeys("10");
Method : 2
WebElement Touch1= dr.findElement(By.xpath("//*[#class='android.widget.EditText']"));
//
TouchAction action = new TouchAction(dr);
action.press(168,440);
action.waitAction(300);
action.perform();
Method : 3
dr.tap(168,440,405,591);
Method : 4
WebElement DOBsample = dr.findElementByXPath("//*[text()[contains(.,'20')]]");
DOBsample.click();
Method : 5
dr.sendKeyEvent(66);
For pickers, you must use swiping over them. I´m using Scala, but logic is obvious:
def setYear(year: Int): Unit = {
require(year >= 1915 || year <= 2015)
val picker = drvr.findElementById("cz.app.yearPicker")
while (picker.getText != year.toString) {
if (picker.getText.toInt > year) {
swipePickerDown(picker)
} else { swipePickerUp(picker) }
}
}
def swipePickerUp(picker: AndroidElement): Unit = {
picker.swipe(SwipeElementDirection.UP, 400)
}
def swipePickerDown(picker: AndroidElement): Unit = {
picker.swipe(SwipeElementDirection.DOWN, 400)
}

not able to select date from date picker

I have recorded selenium code for selecting date from date picker. While running the test case, the date picker pops up and highlights the selected date correctly. But the date is not selected.
The code looks like:-
driver.findElement(By.id("imgStartDate")).click();
driver.findElement(By.xpath("//td[5]")).click();
driver.findElement(By.xpath("//td[5]")).click();
driver.findElement(By.xpath("//td[5]")).click();
driver.findElement(By.xpath("//td[5]")).click();
// ERROR: Caught exception [Error: locator strategy either id or name must be specified explicitly.]
This exception appears in the recorded code only.I am using selenium-server-standalone-2.45.0 jar.
Recording will not work for date picker... try this code.
try{
WebElement dateWidget = driver.findElement(By.xpath(OR.getProperty(object)));
List<WebElement> rows = dateWidget.findElements(By.tagName("tr"));
List<WebElement> columns = dateWidget.findElements(By.tagName("td"));
for (WebElement cell: columns){
if (cell.getText().equals(data)){
cell.findElement(By.linkText(data)).click();
break;
}
}
}catch(Exception e){
return Constants.KEYWORD_FAIL+" -- Not able to select the date"+e.getMessage();
}

Select DropDown option using selenium

If someone could help me with this mystery.. Here is the url
Here if you can see the Date of Birth Fields I am able to select the Month and Date but I am not able to select Year
I Tried selecting Using Value, Index it did not work the same code worked for Month and Date
Below is My Code:
WebElement W = driver.findElement(By.xpath("//html/body/form[#id='aspnetForm'][contains(#action,'ActivateAccount.aspx?key=')][#method='post'][#name='aspnetForm']/div[#class='border4']/div[#id='page']/div[#class='IE-SCroll-mid']/div/div[#class='change-info-contain']/div/div/div/label[3]/select"));
Select dropdown = new Select(W);
dropdown.selectByValue("1997");
Try implementing explicit wait with that. That will make sure the elemenet is present before start looking for that.
By byId = By.id("ctl00_mcp_ddlYear");
//use explicit wait to make sure the element is there
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(byId));
Select dropdown = new Select(myDynamicElement);
dropdown.selectByValue("1997");
You can also use the cssSelector directly wait for the specific option to be present with the following code
//explicit wait
By byCss = By.cssSelector("#ctl00_mcp_ddlYear>option[value='1997']");
WebElement element = new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(byCss));
element.click();

java to excel date formatting

The problem is when I'm running my application and have a grid (with strings and date columns) and save it as an excel file.
When I save it for the first time everything is correctly formatted, but when I try to save the same exact grid again a second time, the date formatting is gone (it's just a float value that when i right click and format to a dateTime object works). When I restart my app it will work again for the first time, then lose formatting again
the code looks like this:
Calendar calendar = Calendar.getInstance();
calendar.setTime((Date)data);
Date gmtDate = new Date(((Date) data).getTime() + (calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET)));
writableCell = new jxl.write.DateTime(sheetColumn, sheetRow, gmtDate, jxl.write.DateTime.GMT);
cellFormat = new jxl.write.WritableCellFormat (new jxl.write.DateFormat("m/d/yyyy h:mm");
writableCell.setCellFormat(cellFormat);
sheet.addCell(writableCell);
I kept break-pointing and everything is as it should be (it always knew it was a dateTime type before going in to the sheet), so I don't think it's from the code.
Has anyone else run into this issue?
Try to define a static WritableCellFormat which takes care of the date formatting.
// Required classes.
import java.util.TimeZone;
import jxl.write.DateFormat;
import jxl.write.DateTime;
import jxl.write.WritableCellFormat;
// Defined once.
public static final WritableCellFormat DATE_CELL_FRMT;
static {
DateFormat df = new DateFormat("MM/dd/yyyy hh:mm");
df.getDateFormat().setTimeZone(TimeZone.getTimeZone("GMT"))
DATE_CELL_FRMT = new WritableCellFormat(df);
}
// Usage
writableCell = new DateTime(sheetColumn, sheetRow, gmtDate, DATE_CELL_FRMT);
Try this:
cellFormat = new jxl.write.WritableCellFormat (new jxl.write.DateFormat("MM/dd/yyyy hh:mm");
It seems that your question is similar to "jExcelApi - cell date format reusing doesn't work". Probably, answer for that question help you with your problem.
Retelling of answer:
According to FAQ (question: "I'm getting the error message 'too many different cell formats'") formats cannot be reused in different sheets because they are not designed to be reused this way
In your case, code may be like this:
WritableCellFormat format = new jxl.write.WritableCellFormat(new jxl.write.DateFormat("m/d/yyyy h:mm"));
for(java.util.Date date : someDateList){
WritableCell cell = new jxl.write.DateTime(someColumn, someRow, date, format);
sheet.addCell(cell);
}

Categories