How to perform click on a string value? - selenium

I want to click a variable value which is stored in a string and below is my code.
OrderConfirmationData orderConfirmationData= (OrderConfirmationData)Serenity.sessionVariableCalled("OrderConfirmationData");
int maxtries=0;
System.out.println("Order is available in NTI" + EfloristConstants.lastname.get());
List<WebElement> recordcount = getDriver().findElements(By.xpath("//table[contains(#id,'ctrlDWController1_DWDetails1_gvNTI')]/*/tr[not(contains(#style,'bold'))]"));
int j=16;
for(int i=1;i<=recordcount.size();i++) {
j=j*i;
String record = "(//table[contains(#id,'ctrlDWController1_DWDetails1_gvNTI')]/*/tr[not(contains(#style,'bold'))]/td)["+j+"]";
String recipientname= element(By.xpath(record)).getTextValue();
if(recipientname.equals(orderConfirmationData.getShipFirstName() != null)) {
System.out.println("Order is available ");
}
j=16;
}
want to click on the recipientname when the, if the condition matches i.e want to perform click inside the If condition.

Add the below line in if condition:
element(By.xpath(record)).click()

Related

Searching and Selecting value from dropdown using selenium Webdriver

I want to know how to select a specific value from dropdown from a pool of values.
My logic is
1.Open the page
2.Fetch all the values from dropdown in list
3.Use a loop
4.Look for that value
5.If the value is not there,select the value x
For me it is saying No such Element Exception
Is it do we need to focus on that element first
In my code i want to select Nextran Corporation
Below is my code
#Test(dependsOnMethods={"go2personalsettings"})
void setru()
{
driver.switchTo().frame("contentFrame");
Select rudropdown=new Select(driver.findElement(By.id("DefaultOrganisationDropDown")));
List<WebElement> drop=rudropdown.getOptions();
int e=drop.size();
String actual_ru="999425, NEXTRAN CORPORATION - JACKSONVILLE";
for(int i=0;i<e;i++)
{
String expected_ru=drop.get(i).getText();
if(!expected_ru.equals(actual_ru))
{
rudropdown.selectByValue(actual_ru);
}
}
Try This:
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//li[contains(text(),'" + ElementValue + "')]")));
WebElement webElement = driver.findElement(By.xpath("//li[contains(text(),'" + ElementValue + "')]"));
webElement.click();
The logic in your code doesn't match what you stated was your intent. You stated that you want to select a particular value from the dropdown, if it exists. If it doesn't, select value 'x'. Your code doesn't ever select value 'x' so I'm not sure what 'x' is but you can fill that in below. Basically the code attempts to select the expected value. If that expected value does not exist, it will throw an exception which is caught and then 'x' is selected. If it does exist, the value is selected and selecting 'x' is skipped.
driver.switchTo().frame("contentFrame");
Select rudropdown = new Select(driver.findElement(By.id("DefaultOrganisationDropDown")));
String actual_ru = "999425, NEXTRAN CORPORATION - JACKSONVILLE";
try
{
rudropdown.selectByValue(actual_ru);
}
catch (NoSuchElementException e)
{
// expected value does not exist, select the value x instead
rudropdown.selectByValue("x");
}

How to write data into excel in a row/column in Sorted Form- ( i am using JXL ), Used Collection.sort(list) but not working

I am Not getting ---
I need to Pick list items in E commerce application search box . and Have to Print each Line By line in a column or any number of rows and column, in Excel in sorted form
i am able to get the name of items in the Search and print them in eclipse console.
what can be the logic to Print them one after other in Excel in sorted form , do i need to save them all in an array first or something else .
Here in this Code I am Getting -- Items From the Search box in the E commerce Application and printing them in the Excel.
Need the logic that any random number of search items gets printed in the Excel in sorted Form
i used the code below to print all the search list items in the Column(Excel) ,what change can be made to print them in sorted order
// picking list items//
List <WebElement> listItems = driver.findElements(By.xpath(".//form[#class='_1WMLwI']//ul/li"));
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
String[] text = new String[10];
arrylngth=listItems.size();
System.out.println("Length of arrylngth" + arrylngth);
for (int col = 0; col < arrylngth; col++)
{ text[col]=listItems.get(col).getText();
System.out.println("Original List "+" "+ text[col]);
// insert data into Excel sheet
for (int row = 0; row <1 ; row++) {
// create an empty array list with an initial capacity
List<String> arrlist = new ArrayList<String>();
// use add() method to add elements in the list
arrlist.add(text[col]);
Collections.sort(arrlist);
System.out.println("sorted Array "+" "+ arrlist);
for(String counter: arrlist){
System.out.println("After Sorting:"+""+ counter);}
Label label1 = new Label(row,col,text[col]);
try {
shSheet.addCell(label1);
} catch (RowsExceededException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
I got the Answer :
Step 1: Need to pick the List Web-Elements -
List <WebElement> listItems = driver.findElements(By.xpath(".//form[#class='_1WMLwI']//ul/li"));
Step 2: Need To Create a String List where i can store the list elements name ( as collection.sort() applied to sting list)
List<String> al = new ArrayList<String>();
Step 3: Apply For Loop to insert data into the String List
for (int i = 0; i <listItems.size(); i++)
{
al.add(listItems.get(i).getText());
System.out.println("Unsorted list " + al);
}
Step 4: Apply Collection.sort() onto the string List , it will Sort the List content
Collections.sort(al);
step 5: Now there is a need to print the sorted list in the Console\
for (String list:al)
{
System.out.println("sorted list"+ " " + al);
}
as we are done with sorted String list , now its an easy task to write the Sorted list into the Excel using JXL or POI using, Write Excel code.

Android Studio SQLite Column Sum

I have a table with several columns and I'm looking to create a function that will return the sum of all the entries in a particular column.
For debug purposes, I've simply set the return string to "1" to confirm the rest of my code works properly, which it does.
Can anyone help me with the necessary code to sum the column and return the value?
public String TotalServings(){
SQLiteDatabase db = getReadableDatabase();
//From the table "TABLE_PRODUCTS" I want to sum all the entries in the column "COLUMN_SERVINGS"
String Servings = "1";
return Servings;
}
Here's what you need:
//This method returns an int, if u need it string parse it
public Int TotalServings(){
int serving =0;
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT SUM(COLUMN_SERVINGS) FROM TABLE_PRODUCTS", null);
if(cursor.moveToFirst()) {
serving = cursor.getInt(0);
}
return serving;
}

How to verify character count of text field?

I want to check the number of characters I can insert in a text field, and was thinking of using 'for loop' but it would not help as Selenium tries to insert more than required character the field will not accept but test goes on without any failure, so is there a way to get character count of the text field?
Would this work?
final String myLongString = "Something horrrrribly looooong";
final int longStringLength = myLongString.length();
// assuming driver is a healthy WebDriver instance
WebElement elem = driver.findElement(By.id("myInput"));
elem.sendKeys(myLongString);
// it's possible that you'll first need to lose focus on elem before the next line
int realLength = elem.getValue().length();
assertEquals(longStringLength, realLength);
Using Protractor I captured the actual text in the field and then did a forloop to count each letter.
element(by.css('elementPATH')).getAttribute('value').then(function(words){
//forloop to count each word
var x = 0
for(var i = 0; i < words.length; i++) {
x = x + 1;
};
//check condition
expect(x).toBe(200);
return true;
});
Let me know if this helps.

inserting data selected by checkboxes

I am trying a code where I want to create a table and insert data into the table.
I want to create table and insert data for only those fields which are selected by user using checkbox.
This is my jsp code:
<%# page language="java" import="java.util.*"%>
<%# page import="java.sql.*" %>
<%
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://";
Connection con = DriverManager.getConnection(url,"sa","SQL1423#3");
Statement st=null;
String select[] = (String[]) session.getAttribute("a");
String tblname=(String)session.getAttribute("tblname");
//out.println(tblname);
//String select[] = request.getParameterValues("id");
if (select != null && select.length != 0)
{
for (int i = 0; i < select.length; i++)
{
int ch=Integer.parseInt(select[i]);
//int counter=1;
//int ID=1;
switch(ch)
{
case 1 :
String idOne=request.getParameter("idOne");
//out.println(idOne);
String idOneIns="insert into "+tblname+" (ID) values(?)";
PreparedStatement pstmt = con.prepareStatement(idOneIns);
pstmt.setString(1, idOne);
//st=con.createStatement();
int valueTwo = pstmt.executeUpdate();
out.println("Inserted");
break;
case 2 :
String ser=request.getParameter("series");
String serIns="insert into "+tblname+" (SERIES) values(?)";
PreparedStatement pst = con.prepareStatement(serIns);
pst.setString(1, ser);
int value = pst.executeUpdate();
out.println("Inserted");
break;
case 3 :
String sym=request.getParameter("symbol");
String symIns="insert into "+tblname+" (SYMBOL) values(?)";
PreparedStatement pstm = con.prepareStatement(symIns);
pstm.setString(1, sym);
int valueOne = pstm.executeUpdate();
out.println("Inserted");
break;
}//switch
}//for
}//if
st.close();
con.close();
}//try
catch(Exception e)
{
out.println(e);
}
%>
Here data is inserted in the table.But if I select all three checkboxes then data is inserted as :
Id Series Symbol
1 null null
null a null
null null b
But I want the data to be inserted as :
Id Series Symbol
1 a b
What changes I should make so that I'll get this output?
Updating the database is better put into a Controller. JSP pages is better used for displaying results (See MVC pattern)
Using dynamic SQL to determine database tables is inherently dangerous and could be targeted for attacks
Your current code loops over input elements, and for each element inserts a new row in the database table. What you want to do is assemble the tree values (from your form input) and insert only one row. E.g.
INSERT INTO table (ID, SERIES, SYMBOL) VALUES (?,?,?)