How to setText in a textArea from an ArrayList? - arraylist

I have an ArrayList ArrayList<String> externalDataList = new ArrayList<>(1600);and I would like to display in a textArea first 3 strings, but I can't succed:
Here is my code
textareaShowPreview.setPrefRowCount(3);
Iterator<String> it = externalDataList.iterator();
int tot = 0;
while(it.hasNext() && tot<3){
String element = it.next();
textareaShowPreview.setText(element + "\n");
System.out.println("elements are: " + element);
tot++;
}
The sout correctly print first 3 strings
element are: 23/05/2007 ,30.9455,31.2545,30.9091,30.9545,7518142
element are: 24/05/2007 ,30.6545,31.0909,30.5364,30.6909,12851606
element are: 25/05/2007 ,30.6636,30.8545,30.4818,30.8091,9392088
but in textArea I have only first one
How do I have to modify my code to show in textArea all three strings, one string per row?

Use appendText instead of setText here is a link.
The setText, delete the previous text and set the text you are giving to it. The append keep the current text in your text area.
Hope it helps!

Related

Get error [object Text]. It should be an element

Trying to get the text from the div with xPath. Finds information in the browser good, but when i try to run with an idea than i get error:"is: [object Text]. It should be an element."
List<WebElement> priceGameWebElement = webDriver.findElements(By.xpath("//div[contains(#class,'search_price')]" +
"/text()[normalize-space()][1]"));
What do I need to do to make everything work?
You can "interrupt" your query before the /text()... part like this:
List<WebElement> priceGameWebElement = webDriver.findElements(By.xpath("//div[contains(#class,'search_price')]"));
Then you should get a List<WebElement> which contains the elements with the text() nodes for further distinction. They could probably be queried with the .getText() function.
If for some reason you cannot exclude text() from XPath and you need just extract the text of the element, then there is a workaround: use method document.evaluate() from JavaScript.
Code example:
String textObjectXpath = "\"//*[local-name() = 'text'][#x='8']/text()\"";
String script = "var element = document.evaluate("
+ textObjectXpath
+ ", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;"
+ "if (element) {return element.nodeValue;}";
String extractedText = (String) ((JavascriptExecutor)driver).executeScript(script);
The if statement "if (element) {return element.nodeValue;}" could be omitted if you don't care about the scenario when the element will be without text. In a such case, you may want to replace the line with "return element.nodeValue;"

How to get NPOI Excel RichStringCellValue?

I am using DotNetCore.NPOI (1.2.1) in order to read an MS Excel file.
Some of the cells are of type text and contain formatted strings (e.g. some words in bold).
How do I get the formatted cell value? My final goal: Retrieve the cell text as HTML.
I tried
var cell = row.GetCell(1);
var richStringCellValue = cell.RichStringCellValue;
But this won't let me access the formatted string (just the plain string without formattings).
Does anybody have an idea or solution?
I think you'll have to take longer route in this case. First you'll have to maintain the formatting of cell value like date, currency etc and then extract the style from cell value and embed the cell value under that style.
best option is to write extenstion method to get format and style value.
To get the fomat Please see this link How to get the value of cell containing a date and keep the original formatting using NPOI
For styling first you'll have to check and find the exact style of running text and then return the value inside the html tag , below method will give you idea to extract styling from cell value. Code is untested , you may have to include missing library.
public void GetStyleOfCellValue()
{
XSSFWorkbook wb = new XSSFWorkbook("YourFile.xlsx");
ISheet sheet = wb.GetSheetAt(0);
ICell cell = sheet.GetRow(0).GetCell(0);
XSSFRichTextString richText = (XSSFRichTextString)cell.RichStringCellValue;
int formattingRuns = cell.RichStringCellValue.NumFormattingRuns;
for (int i = 0; i < formattingRuns; i++)
{
int startIdx = richText.GetIndexOfFormattingRun(i);
int length = richText.GetLengthOfFormattingRun(i);
Console.WriteLine("Text: " + richText.String.Substring(startIdx, startIdx + length));
if (i == 0)
{
short fontIndex = cell.CellStyle.FontIndex;
IFont font = wb.GetFontAt(fontIndex);
Console.WriteLine("Bold: " + (font.IsBold)); // return string <b>my string</b>.
Console.WriteLine("Italics: " + font.IsItalic + "\n"); // return string <i>my string</i>.
Console.WriteLine("UnderLine: " + font.Underline + "\n"); // return string <u>my string</u>.
}
else
{
IFont fontFormat = richText.GetFontOfFormattingRun(i);
Console.WriteLine("Bold: " + (fontFormat.IsBold)); // return string <b>my string</b>.
Console.WriteLine("Italics: " + fontFormat.IsItalic + "\n");// return string <i>my string</i>.
}
}
}
Font formatting in XLSX files are stored according to schema http://schemas.openxmlformats.org/spreadsheetml/2006/main which has no direct relationship to HTML tags. Therefore your task is not that much straight forward.
style = cell.getCellStyle();
font = style.getFont(); // or style.getFont(workBook);
// use Font object to query font attributes. E.g. font.IsItalic
Then you will have to build the HTML by appending relevant HTML tags.

Getting all the cell values from table using table header using Webdriver

Below is the HTML code for the tables:
I need to extract values from table preceding with header as "Opportunities".
Could someone please suggest the best way forward as I can extract values fine if they belong to the same table but I need help when they are in two different table and i need to look for table opportunities and than extract data from the preceding table.
Sure here is my best interpretation of what you need in Java. Any questions and I'll alter my solution to accommodate them. This starts with an index of 0,0 for row and column.
int row = 0, column = 1; //it's 1 to accommodate fogr the first thing you want being a 'th' tag
List<WebElement> tableRows = driver.findElements(By.className("dataRow"));//this gets all elements on your page with a class of dataRow (which are your tr's)
for(WebElement singleRow: tableRows) //this for loop increments each of these tr's
{
System.out.println(singleRow.findElement(By.xpath("th[1]/a[1]")).getText()); //I'll have to use an xpath here because I don't have time to play around with other solutions but it'll work
System.out.println("Row: " + row + ", Column: " + column);
List<WebElement> rowTDs = singleRow.findElements(By.tagName("td"));//this gets every td in the current tr and puts it into a list
for(WebElement singleTD: rowTDs) //this increments through that list of td's
{
System.out.println(singleTD.getText()); //this gives you back the text contained in that cell
System.out.println("Row: " + row + ", Column: " + column);
column++; //increment the column counter
}
column=1; //reset the column
row++; //increment the row counter
}
Edit: It seems that given that element of the request "Saykiro" has almost the right of it and you can replace in my solution tableRows = with this, there's probably a more succinct way to get the second table but this is what comes to me:
WebElement table1 = driver.findElemen(By.id("001Z000000vrLQe_RelatedOpportunityList_title"));
WebElement table2 = table1.findElement(By.xpath("../../../../following-sibling::table"))
List<WebElement> tableRows = table2.findElements(By.className("dataRow"));
For your case:
//*[table/tbody/tr/td/h3[text()='Opportunities']]/table[2]//td[#class=' dataCell ']
For C# (getting list of values in cells):
var values = driver.FindElements(By.XPath("//*[table/tbody/tr/td/h3[text()='Opportunities']]/table[2]//td[#class=' dataCell ']")).Select(a=>a.Text);
You should describe outer part of html, so we can build xpath better.

ALIGN_JUSTIFIED for iText list item

I want to set alignment to list items by writing this code -
ListItem alignJustifiedListItem =
new ListItem(bundle.getString(PrintKeys.AckProcess), normalFont8);
alignJustifiedListItem.setAlignment(Element.ALIGN_JUSTIFIED);
I see this doesn't make any change on alignment (defaulted as left aligned). Changing it to
alignJustifiedListItem.setAlignment(Element.ALIGN_JUSTIFIED_ALL); is actually working but then the last line of the content also expands (as mentioned in doc, as well)
I dont understand when ListItem extends Paragraph, how setAlignment() behaviour can change. I don't see any overriding as well.
Please take a look at the ListAlignment example.
In this example, I create a list with three list items of which I set the alignment to ALIGN_JUSTIFIED:
List list = new List(List.UNORDERED);
ListItem item = new ListItem(text);
item.setAlignment(Element.ALIGN_JUSTIFIED);
list.add(item);
text = "a b c align ";
for (int i = 0; i < 5; i++) {
text = text + text;
}
item = new ListItem(text);
item.setAlignment(Element.ALIGN_JUSTIFIED);
list.add(item);
text = "supercalifragilisticexpialidocious ";
for (int i = 0; i < 3; i++) {
text = text + text;
}
item = new ListItem(text);
item.setAlignment(Element.ALIGN_JUSTIFIED);
list.add(item);
document.add(list);
If you look at the result, you can see that the alignment works as expected:
I deliberately introduced a very long word such as "supercalifragilisticexpialidocious" to show you that all lines but the last are indeed justified.
Update:
In a comment, you claim that the alignment is wrong when you introduce the \ character, and you want me to fix iText. However, there is nothing to fix.
I have adapted the original example like this:
text = "a b c align ";
for (int i = 0; i < 5; i++) {
text = text + "\\" + text;
}
item = new ListItem(text);
item.setAlignment(Element.ALIGN_JUSTIFIED);
list.add(item);
text = "supercalifragilisticexpialidocious ";
text = text + text;
text = text + text;
text = text + "\n" + text;
item = new ListItem(text);
item.setAlignment(Element.ALIGN_JUSTIFIED);
list.add(item);
In the first case, I have introduce the \ character. This didn't change anything to the behavior of the ListItem. In the second case, I introduce a newline character. The result was as expected: a newline character was introduced and the last line of every "paragraph" that was defined by the newline character was indeed not justified. That is what one would normally expect. I would introduce a bug if I would change this.
This is the screen shot of the result:
The introduction of the '\' character in the lines with "a b c align " doesn't have any effect on the alignment. The introduction of the newline half way the "supercalifragilisticexpialidocious " part breaks the list item in two parts. The final line of each part is not justified, which is the desired behavior.
If you do not want this desired behavior, you have to parse the content first and remove all newlines characters (carriage return and line feed).
Update:
In a new comment, you mention the '\' character as an escape character for the ''' character (actually the \' character). I have adapted the original example once more:
text = "a b c\' align ";
for (int i = 0; i < 5; i++) {
text = text + text;
}
item = new ListItem(text);
item.setAlignment(Element.ALIGN_JUSTIFIED);
list.add(item);
The result looks like this:
The text is justified correctly. However, I can imagine that problems can occur if you handle Strings with escape characters incorrectly. In this case, the '\'' character was hardcoded. If you obtain the String from a database and you read that String incorrectly, then you can have strange results. Especially from my days as a PHP developer, I remember instances where a single quote ended up to be stored like this '\\\'' in a database if you didn't watch out.

Insert text into flex 3 textarea

I have a textArea and a list. When a user double clicks a list item, the label of the selected item should be inserted into the textarea. When a text is selected in the textArea, it should be replaced, otherwise the text just needs to be inserted into the existing text at the caret point.
I've managed to get the text and everything, I just can't manage to insert it at the caret point. Does anyone know how to do this?
It's actually not JavaScript but Adobe Flex 3. Thanks for the help though, it did push me in the right direction. This is the way its done in Flex 3:
var caretStart:int = textArea.selectionBeginIndex;
var caretEnd:int = textArea.selectionEndIndex;
textArea.text = textArea.text.substring(0,caretStart)
+ newText
+ textArea.text.substr(caretEnd);
The accepted answer works great if you do not have existing HTML formatting. In my case, I inserted a new button into the editor that the user could click to put in a key word. I kept losing all HTML formatting until I dug around in the actual class and sided with a TextRange object:
public function keyWord_Click(event:Event) : void
{
var caretStart:int = txtEditor.textArea.selectionBeginIndex;
var caretEnd:int = txtEditor.textArea.selectionEndIndex;
var newText : String = "[[[KEYWORD]]]";
var tf:TextRange = new TextRange(txtEditor,true,caretStart,caretEnd);
tf.text = newText;
}
The nice thing about this approach is, you can also apply conditional formatting to that TextRange object as needed.
You can use txtarea.selectionStart and txtarea.selectionEnd to get Selected text position.
After that, You delete txt and add new selected text.
I don't known much about Javascript, so I wrote it for U.
You can search on google with keywords:
"Javascript Selected Text TextArea"
"Javascript add text at position"
Sample code:
function insertAtCursor(myField, myValue) {
//IE support
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
//MOZILLA/NETSCAPE support
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ myValue
+ myField.value.substring(endPos, myField.value.length);
} else {
myField.value += myValue;
}
caretPos = doGetCaretPosition(myField);
alert(caretPos);
setCaretPosition(myField,caretPos-3);
}