create tableview using html content in android - java

I have to develop one android native application using stringbuffer with html content.
Here i have used below code:
PayPalInvoiceItem item1 = new PayPalInvoiceItem();
sb.append("<html><body><table>");
for (int i = 0; i < Constants.mItem_Detail
.size(); i++) {
String title = Constants.mItem_Detail
.get(i).get(
SingleMenuItem.KEY_PNAME);
String qty = Constants.mItem_Detail.get(i)
.get(SingleMenuItem.KEY_QTY);
String cost = Constants.mItem_Detail.get(i)
.get(SingleMenuItem.KEY_PRICE);
String total = Constants.mItem_Detail
.get(i).get(
SingleMenuItem.KEY_TOTAL);
total_count=total_count+Integer.parseInt(qty);
StringBuffer buffer = sb.append("<tr>" + "<td>" + title
+ "</td><td>" + qty + " * " + cost
+ "</td>" + " = <td>" + total
+ " " + "</td></tr>");
item1.setName(buffer.toString());
Now i have to run the application means my output is looking like
<html><body><table>"<tr>" "<td>"krishna
"</td><td>" 1 " * " 100
+ "</td>" = <td>" 100
+ " " + "</td></tr>
But i need the o/p like:
krishna 1 100 100
veni 2 30 60
How can i do????
please help me ???
EDIT:
here i have to change the below line item1.setName(buffer.toString());
to
item.setName(buffer.toString(), "text/html; charset=utf-8"); means am getting following error:
The method setName(String) in the type PayPalInvoiceItem is not applicable for the arguments (String,
String)
How can i resolve these error ????

What is the 'item' you are trying to setName on? by the sounds of things you probably just need to create a WebView like this:
WebView view = new WebView(this);
view.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
view.loadData(stringBuffer.toString(), "text/html", "UTF-8");
setContentView(view);
you also seem to have not terminated the HTML correctly i.e your last write to the StringBuffer should be:
stringBuffer.append("</table></body></html>");
also check your line:
total_count=total_count+Integer.parseInt(qty);
should it not be:
total_count=total_count+Integer.parseInt(total);

Related

I can't set a string in a TextView in an Android app (using Java)

I'm building a simple calculator Android app in Java that will receive 2 numbers as inputs and when the user presses one of the 4 action buttons (+, -, *, /) the exercise and it's solution will appear in the bottom of the screen inside a TextView in this format:
{num1} {action} {num2} = {solution}
I tried to declare a string and form the exercise's string in it and in the end I used "setText" to change the TextView but instead of showing the full exercise when I run the app it shows something like "androidx.appcompat.widget.AppCom".
Here is an example for the string I form when the user clicks on the + button:
exerciseStr = etNum1.toString() + " + " + etNum2.toString() + " = " + String.valueOf(Integer.valueOf(etNum1.getText().toString())+Integer.valueOf(etNum2.getText() + ""));
Does anybody know what the issue may be?
You should call getText() befor calling toString():
exerciseStr = etNum1.getText().toString() + " + " + etNum2.getText().toString() + " = " + String.valueOf(Integer.valueOf(etNum1.getText().toString())+Integer.valueOf(etNum2.getText() + ""));
Change it to like this.
exerciseStr = etNum1.getText().toString() + " + " + etNum2.getText().toString() + " = " + String.valueOf(Integer.valueOf(etNum1.getText().toString())+Integer.valueOf(etNum2.getText() + ""));

Parse html content for a value

I receive a Http response after a call as Html String and I would like to scrape certain value stored inside the ReportViewer1 variable.
<html>
....................
...........
<script type="text/javascript">
var ReportViewer1 = new ReportViewer('ReportViewer1', 'ReportViewer1_ReportToolbar', 'ReportViewer1_ReportArea_WaitControl', 'ReportViewer1_ReportArea_ReportCell', 'ReportViewer1_ReportArea_PreviewFrame', 'ReportViewer1_ParametersAreaCell', 'ReportViewer1_ReportArea_ErrorControl', 'ReportViewer1_ReportArea_ErrorLabel', 'ReportViewer1_CP', '/app/Telerik.ReportViewer.axd', 'a90a0d41efa6429eadfefa42fc529de1', 'Percent', '100', '', 'ReportViewer1_EditorPlaceholder', 'ReportViewer1_CalendarFrame', 'ReportViewer1_ReportArea_DocumentMapCell', {
CurrentPageToolTip: 'STR_TELERIK_MSG_CUR_PAGE_TOOL_TIP',
ExportButtonText: 'Export',
ExportToolTip: 'Export',
ExportSelectFormatText: 'Export to the selected format',
FirstPageToolTip: 'First page',
LabelOf: 'of',
LastPageToolTip: 'Last Page',
ProcessingReportMessage: 'Generating report...',
NoPageToDisplay: 'No page to display.',
NextPageToolTip: 'Next page',
ParametersToolTip: 'Click to close parameters area|Click to open parameters area',
DocumentMapToolTip: 'Hide document map|Show document map',
PreviousPageToolTip: 'Previous page',
TogglePageLayoutToolTip: 'Switch to interactive view|Switch to print preview',
SessionHasExpiredError: 'Session has expired.',
SessionHasExpiredMessage: 'Please, refresh the page.',
PrintToolTip: 'Print',
RefreshToolTip: 'Refresh',
NavigateBackToolTip: 'Navigate back',
NavigateForwardToolTip: 'Navigate forward',
ReportParametersSelectAllText: '<select all>',
ReportParametersSelectAValueText: '<select a value>',
ReportParametersInvalidValueText: 'Invalid value.',
ReportParametersNoValueText: 'Value required.',
ReportParametersNullText: 'NULL',
ReportParametersPreviewButtonText: 'Preview',
ReportParametersFalseValueLabel: 'False',
ReportParametersInputDataError: 'Missing or invalid parameter value. Please input valid data for all parameters.',
ReportParametersTrueValueLabel: 'True',
MissingReportSource: 'The source of the report definition has not been specified.',
ZoomToPageWidth: 'Page Width',
ZoomToWholePage: 'Full Page'
}, 'ReportViewer1_ReportArea_ReportArea', 'ReportViewer1_ReportArea_SplitterCell', 'ReportViewer1_ReportArea_DocumentMapCell', true, true, 'PDF', 'ReportViewer1_RSID', true);
</script>
...................
...................
</html>
The value is a90a0d41efa6429eadfefa42fc529de1 and this is in the middle of this content:
'/app/Telerik.ReportViewer.axd', 'a90a0d41efa6429eadfefa42fc529de1', 'Percent', '100',
Whats the best way I can parse this value using Java?
Parse the HTML with String class
public class HtmlParser {
public static void main(String args[]){
String result = getValuesProp(html);
System.out.println("Result: "+ result);
}
static String PIVOT = "Telerik.ReportViewer.axd";
public static String getValuesProp(String json) {
String subString;
int i = json.indexOf(PIVOT);
i+= PIVOT.length();
//', chars
i+=2;
subString = json.substring(i);
i = subString.indexOf("'");
i++;
subString = subString.substring(i);
i = subString.indexOf("'");
subString = subString.substring(0,i);
return subString;
}
static String html ="<html>\n" +
"\n" +
"<script type=\"text/javascript\">\n" +
" var ReportViewer1 = new ReportViewer('ReportViewer1', 'ReportViewer1_ReportToolbar', 'ReportViewer1_ReportArea_WaitControl', 'ReportViewer1_ReportArea_ReportCell', 'ReportViewer1_ReportArea_PreviewFrame', 'ReportViewer1_ParametersAreaCell', 'ReportViewer1_ReportArea_ErrorControl', 'ReportViewer1_ReportArea_ErrorLabel', 'ReportViewer1_CP', '/app/Telerik.ReportViewer.axd', 'a90a0d41efa6429eadfefa42fc529de1', 'Percent', '100', '', 'ReportViewer1_EditorPlaceholder', 'ReportViewer1_CalendarFrame', 'ReportViewer1_ReportArea_DocumentMapCell', {\n" +
" CurrentPageToolTip: 'STR_TELERIK_MSG_CUR_PAGE_TOOL_TIP',\n" +
" ExportButtonText: 'Export',\n" +
" ExportToolTip: 'Export',\n" +
" ExportSelectFormatText: 'Export to the selected format',\n" +
" FirstPageToolTip: 'First page',\n" +
" LabelOf: 'of',\n" +
" LastPageToolTip: 'Last Page',\n" +
" ProcessingReportMessage: 'Generating report...',\n" +
" NoPageToDisplay: 'No page to display.',\n" +
" NextPageToolTip: 'Next page',\n" +
" ParametersToolTip: 'Click to close parameters area|Click to open parameters area',\n" +
" DocumentMapToolTip: 'Hide document map|Show document map',\n" +
" PreviousPageToolTip: 'Previous page',\n" +
" TogglePageLayoutToolTip: 'Switch to interactive view|Switch to print preview',\n" +
" SessionHasExpiredError: 'Session has expired.',\n" +
" SessionHasExpiredMessage: 'Please, refresh the page.',\n" +
" PrintToolTip: 'Print',\n" +
" RefreshToolTip: 'Refresh',\n" +
" NavigateBackToolTip: 'Navigate back',\n" +
" NavigateForwardToolTip: 'Navigate forward',\n" +
" ReportParametersSelectAllText: '<select all>',\n" +
" ReportParametersSelectAValueText: '<select a value>',\n" +
" ReportParametersInvalidValueText: 'Invalid value.',\n" +
" ReportParametersNoValueText: 'Value required.',\n" +
" ReportParametersNullText: 'NULL',\n" +
" ReportParametersPreviewButtonText: 'Preview',\n" +
" ReportParametersFalseValueLabel: 'False',\n" +
" ReportParametersInputDataError: 'Missing or invalid parameter value. Please input valid data for all parameters.',\n" +
" ReportParametersTrueValueLabel: 'True',\n" +
" MissingReportSource: 'The source of the report definition has not been specified.',\n" +
" ZoomToPageWidth: 'Page Width',\n" +
" ZoomToWholePage: 'Full Page'\n" +
" }, 'ReportViewer1_ReportArea_ReportArea', 'ReportViewer1_ReportArea_SplitterCell', 'ReportViewer1_ReportArea_DocumentMapCell', true, true, 'PDF', 'ReportViewer1_RSID', true);\n" +
" </script>\n" +
"\n" +
"</html>";
}
I would read the text a line at a time like how most files are read. Because the format will always be the same, you look for a line that begins with the characters "var ReportViewer1." Then you know you have found the line you want. You may need to strip some white space, although it will always be formatted with the same whitespace too (up to you really.)
When you have the line, use the String .split() method to split that line into an array. There are nice delimiters there to split on ... "," or " " or ", " ... again, see what works best for you.
Test the split up line parts for '/app/Telerik.ReportViewer.axd' ... the next member of your split array will be the value you are looking for.
Again, the formatting will always be the same, so you can rely on that to find your variable. Of course, study the html text to make sure it does always follow the same format within the line you are investigating, but looking at it, I assume it probably does.
Again, find your line ... split it on a delimiter ... and use some logic to find the element you are after in the split up line parts.

Univocity Parsers: Calling a function from here is not working: parserSettings.selectFields( *some_function* );

I am using a .csv file and would like to pass a string constructed by a function to: parserSettings.selectFields( function );
During testing, when the string returned by the function is pasted directly into: parserSettings.selectFields( string ); the parsing works fine, however, when the function is used instead, the parse doesn't work, and there is only output of whitespace.
Here is the function:
public String buildColList() {
//Parse the qty col names string, which is a comma separated string
String qtyString = getQtyString();
List<String> qtyCols = Arrays.asList(qtyString.split("\\s*,\\s*"));
String colString = StringUtils.join(qtyCols.toArray(), "\"" + ", " + "\"");
String fullColString;
fullColString = "\"" + getString1() + "\"" + ", " + "\"" + getString2() + "\"" + ", " + "\"" + colString + "\"" + ", " + "\"" + getString4 + "\"";
return fullColString;
}
Here is how it is placed:
parserSettings.selectFields(buildColList());
Any help would be greatly appreciated, thanks.
You need to return an array from your buildColList method, as the parserSettings.selectFields() method won't split a single string. Your current implementation is selecting a single, big header instead of multiple columns. Change your method to do something like this:
public String[] buildColList() {
//Parse the qty col names string, which is a comma separated string
String qtyString = getQtyString();
List<String> qtyCols = Arrays.asList(qtyString.split("\\s*,\\s*"));
String colString = StringUtils.join(qtyCols.toArray(), "\"" + ", " + "\"");
String[] fullColString = new String[]{getString1(), getString2(), colString, getString4};
return fullColString;
}
And it should work. You might need to adjust my solution to fit your particular scenario as I didn't run this code. Also, I'm not sure why you were appending quotes around the column names, so I removed them.
Hope this helps.

How to set the multiple attributes of objectClass for UnboundID & OpenLDAP via Java 7

I'm not sure how to properly pass the multiple attributes needed for an OpenLDAP insert via UnboundID. I have omitted the objectClass attributes & received a "no objectClass" error. I have also tried comma-separated & the bracket/array route like below & received the "value #0 invalid per syntax" error.
String[] ldifLines = {"dn: ou=users,dc=sub,dc=domain,dc=com", "cn: " + uid, "userPassword: " + pw, "description: user", "uidNumber: " + lclDT, "gidNumber: 504", "uid: " + uid, "homeDirectory: " + File.separator + "home" + File.separator + this.getStrippedUser(), "objectClass: {posixAccount, top}"};
LDAPResult ldapResult = lclLC.add(new AddRequest(ldifLines));
So, the question is, how do I successfully pass these objectClass attributes in the string array included above? Again, I have tried: "objectClass: top, posixAccount" as well. Thanks in advance!
It uses an LDIF representation, so if an attribute has multiple values, then the attribute appears multiple times. Like:
String[] ldifLines =
{
"dn: ou=users,dc=sub,dc=domain,dc=com",
"objectClass: top",
"objectClass: posixAccount"
"cn: " + uid,
"userPassword: " + pw,
"description: user",
"uidNumber: " + lclDT,
"gidNumber: 504",
"uid: " + uid,
"homeDirectory: " + File.separator + "home" +
File.separator + this.getStrippedUser(),
};
LDAPResult ldapResult = lclLC.add(new AddRequest(ldifLines));
Also, the LDAP SDK allows you to use a shortcut and just do it in a single call without the need to create the array or the AddRequest object, like:
LDAPResult ldapResult = lclLC.add(
"dn: ou=users,dc=sub,dc=domain,dc=com",
"objectClass: top",
"objectClass: posixAccount"
"cn: " + uid,
"userPassword: " + pw,
"description: user",
"uidNumber: " + lclDT,
"gidNumber: 504",
"uid: " + uid,
"homeDirectory: " + File.separator + "home" +
File.separator + this.getStrippedUser());

Grouping duplicates till a specific count

I have a number of xml's that come in haphazardly that contain a Ocount, and Lnumber, as well as other data. I have created a class to get that data.
My problem is that how can I group xml's that have the same Lnumber(string), until it reaches the Ocount(int). (the xmls that have the same lnumber has the same Ocount). And eventually send out a email telling with xmls has been processed.
String readLine = FileHandler.checkListFile(sh.getShipmentHeader().getBillToCustomer());
if (!readLine.isEmpty())
{
int orderCount = 0;
int index = readLine.indexOf(";") + 1;
String customerName = readLine.substring(index, readLine.indexOf(";", index)).trim();
index = readLine.indexOf(";", index) + 1;
String to = readLine.substring(index, readLine.length()).trim();
if (!billMap.containsKey(sh.getShipmentHeader().getBillToCustomer()))
{
billMap.put(sh.getShipmentHeader().getBillToCustomer(), 1);
orderCount = 1;
}
else
{
billMap.put(sh.getShipmentHeader().getBillToCustomer(), ((int) billMap.get(sh.getShipmentHeader().getBillToCustomer())) + 1);
orderCount = (int) billMap.get(sh.getShipmentHeader().getBillToCustomer());
}
outboundMessage += sh.getShipmentHeader().getOrderNumber() + li ;
logger.info("On-Demand Outbound Export Info: " + orderCount + " processed out of " + sh.getShipmentHeader().getOrderCount() +
" for " + customerName);
if (orderCount == sh.getShipmentHeader().getOrderCount())
{
Email email = new Email();
billMap.remove(sh.getShipmentHeader().getBillToCustomer());
outboundMessage += li + "Total of #"+ sh.getShipmentHeader().getOrderCount() + " orders processed for "+ customerName + li ;
logger.info("On-Demand Email sent for " + customerName);
System.out.println(outboundMessage);
email.outboundEmail("TEST: Orders for " + customerName + " complete", outboundMessage, to);
outboundMessage = "";
email = null;
}}
I been working on this for days, where am I going wrong.
It seems like you are having difficulty obtaining information from xmls. I suggest using XStream [1]. It is capable of serialising objects to xml and back. By using XStream, you can get an Object from the xml and compare variables (Lnumber and Ocount) easily.
If you insist using this code, I suggest adding comments to notify us what you are doing, but if want an easier alternative to work with xml files using java, I highly suggest using XStream as a solution.
[1] http://x-stream.github.io/

Categories

Resources