I have echo $result in PHP code and I am printing the result to a textview and I want to display it in multiline but I get this in the textView
Available articles: 28
---------------------------------------
number of clients: 23
Top solded Articles and its beneficient:
Muffin Mix - Lemon Cranberry:161.41
Mushrooms - Black, Dried:148.62
Amaretto:134.01
Longos - Grilled Veg Sandwiches:122.89
Here is my android code
public void processFinish(String output) {
TextView reprttxt = (TextView)findViewById(R.id.reprttxt);
output.replace("\\n",System.getProperty("line.separator"));
reprttxt.setText(output);
}
Notice that I tried output.replace("\\n",System.getProperty("line.separator")); and output.replace("\\\n",System.getProperty("line.separator")); but it doesn't work. How to solve that by modifying the Android Java code or the PHP code?
Use a CharSquence instead of a String for output. TextView.setText() doesn't like String text that contains special characters it will either strip it or display it weirdly depending on the circumstance CharSquence doesn't have this problem.
According to this doc you have to set a property like android:maxLines="2". You can set any value you like. Then '\n' should work as you expected.
The string doesn't have a real embedded newline '\n' character. It has a "\\n" substring- an actual backslash followed by an n. The correct way to fix this is by fixing the server- it shouldn't be sending the data like this. If you need a hack, replace "\\n", not "\n"
You can tell this is the case by the fact a \n is in the actual output. If it was just the wrong type of separator, it would either be whitespace or ignored instead. BTW, on Android the line separator is '\n' as it is on all Linux based systems.
public void processFinish(String output) {
TextView reprttxt = (TextView)findViewById(R.id.reprttxt);
reprttxt.setText(Html.fromHtml(output));
}
example : output = "this is \n two line";
Related
I need help to parse, modify and show a string on an Android App (Java language, max API level 22)
This is a example string I'm getting from an API which contains only custom tag:
<BOLD> Something <RED> went wrong </RED> </BOLD> <NEWLINE> Server unreachable </NEWLINE>
I need to remove all this custom tags then format its content based on the tags that were wrapping that substring (so I'm expeting, for example, to get "went wrong" in red color and bold). I already tried looking up for similar problems but can't get to the final result.
The string (cleaned and formatted) will then be used to set the Text of a TextView inside a List View
One way of doing this is like this....
String testString="<BOLD> Something <RED> went wrong </RED> </BOLD> <NEWLINE> Server unreachable </NEWLINE>";
testString=testString.replaceAll("<BOLD>","<font> <b>");
testString=testString.replaceAll("</BOLD>","</b> </font>");
testString=testString.replaceAll("<RED>","<font color =\"#FF0000\">"); //#FF0000 is hex code for red color
testString=testString.replaceAll("</RED>","</font> ");
testString=testString.replaceAll("<NEWLINE>","<br>");
testString=testString.replaceAll("</NEWLINE>","");
TextView textView=findViewById(R.id.text);
textView.setText(Html.fromHtml(testString));
Output :
Using Regex (Regular Expressions)
Just give your string to the Regex Pattern and it removes all the extra tags for you.
Kotlin
This removes all the HTML tags inside your String:
val result = yourString.replace(Regex("(<[a-z]*>)|(<.[a-z]*>)"), "")
Java
String result = yourString.replaceAll("(<[a-z]*>)|(<.[a-z]*>)", "");
I asked someone to developp an android app for me, but forgot to tell him to make the translation for me. I found how on google, by creating multiple string file in the values folder and translate almost all the app.
My problem is some text is written in the java folder. I made string for some but for others I can't. I tried using R.string.txt or #string/txt but it's not working.
If you could help with those codes I would apreciate it.
1- in the first code the text I want to add as string is [débit à passer] & [gouttes/min]
final TextView txt = (TextView) dialogView.findViewById(R.id.text_result);
String dose_qunt="Débit à passer " + "="+dose+" "+"gouttes/min";
2- for the second text: [please enter volume] & [please enter time]
public void onClick(View view) {
hideKeyboard(this);
if(view==btn_min){
if(edt_vol.getText().toString().isEmpty() ){
edt_vol.setError("please enter volume");
}
else if(edt_time.getText().toString().isEmpty()){
edt_time.setError("please enter time");
}
Cordialy
What you have here is a bad practice called "hardcoded strings".
Any strings that are shown to the user really should not be written in the Java source code.
That said, to properly correct such a problem, you need some understanding of Java and Android programming.
I can fix your specific examples with some guesswork, but if there are other such strings in your app, they may need a different solution.
It would really be better for you to ask the person who wrote the app to fix this.
That said, here how it should look:
1. Loading a string with parameters:
<string name="dose">"Débit à passer = %d gouttes/min"</string>
Notice %d is a placeholder for a value supplied when the app runs.
In this example the value can only be an integer. If you need different kind of parameter, like a decimal number, there is a list of placeholders here.
And this is how you load it:
int dose = 10; //just an example
final TextView txt = (TextView) dialogView.findViewById(R.id.text_result);
txt.setText(getString(R.string.dose, dose));
The second case is almost identical, except you do not need a parameter:
please enter volume
And the code will look like this:
if(edt_vol.getText().toString().isEmpty() ){
edt_vol.setError(getString(R.string.volume_error));
}
R.string.nameOfString gives the id of the string.
What you need is to call getString and pass the id:
getString(R.string.some_text);
You have to write this strings in values/string.xml in each language string file:
<string name="debit">Débit à passer </string>
<string name="gouttes">gouttes/min</string>
And later you can use them as:
String dose_qunt=getString(R.string.debit) + "="+dose+" "+getString(R.string.gouttes);
(for example)
If it dosen't works, write:
String dose_qunt= getApplicationContext().getString(R.string.debit) + "="+dose+" "+getApplicationContext().(R.string.gouttes);
And simillar for the second texts.
Does Java have a built-in way to escape arbitrary text so that it can be included in a regular expression? For example, if my users enter "$5", I'd like to match that exactly rather than a "5" after the end of input.
Since Java 1.5, yes:
Pattern.quote("$5");
Difference between Pattern.quote and Matcher.quoteReplacement was not clear to me before I saw following example
s.replaceFirst(Pattern.quote("text to replace"),
Matcher.quoteReplacement("replacement text"));
It may be too late to respond, but you can also use Pattern.LITERAL, which would ignore all special characters while formatting:
Pattern.compile(textToFormat, Pattern.LITERAL);
I think what you're after is \Q$5\E. Also see Pattern.quote(s) introduced in Java5.
See Pattern javadoc for details.
First off, if
you use replaceAll()
you DON'T use Matcher.quoteReplacement()
the text to be substituted in includes a $1
it won't put a 1 at the end. It will look at the search regex for the first matching group and sub THAT in. That's what $1, $2 or $3 means in the replacement text: matching groups from the search pattern.
I frequently plug long strings of text into .properties files, then generate email subjects and bodies from those. Indeed, this appears to be the default way to do i18n in Spring Framework. I put XML tags, as placeholders, into the strings and I use replaceAll() to replace the XML tags with the values at runtime.
I ran into an issue where a user input a dollars-and-cents figure, with a dollar sign. replaceAll() choked on it, with the following showing up in a stracktrace:
java.lang.IndexOutOfBoundsException: No group 3
at java.util.regex.Matcher.start(Matcher.java:374)
at java.util.regex.Matcher.appendReplacement(Matcher.java:748)
at java.util.regex.Matcher.replaceAll(Matcher.java:823)
at java.lang.String.replaceAll(String.java:2201)
In this case, the user had entered "$3" somewhere in their input and replaceAll() went looking in the search regex for the third matching group, didn't find one, and puked.
Given:
// "msg" is a string from a .properties file, containing "<userInput />" among other tags
// "userInput" is a String containing the user's input
replacing
msg = msg.replaceAll("<userInput \\/>", userInput);
with
msg = msg.replaceAll("<userInput \\/>", Matcher.quoteReplacement(userInput));
solved the problem. The user could put in any kind of characters, including dollar signs, without issue. It behaved exactly the way you would expect.
To have protected pattern you may replace all symbols with "\\\\", except digits and letters. And after that you can put in that protected pattern your special symbols to make this pattern working not like stupid quoted text, but really like a patten, but your own. Without user special symbols.
public class Test {
public static void main(String[] args) {
String str = "y z (111)";
String p1 = "x x (111)";
String p2 = ".* .* \\(111\\)";
p1 = escapeRE(p1);
p1 = p1.replace("x", ".*");
System.out.println( p1 + "-->" + str.matches(p1) );
//.*\ .*\ \(111\)-->true
System.out.println( p2 + "-->" + str.matches(p2) );
//.* .* \(111\)-->true
}
public static String escapeRE(String str) {
//Pattern escaper = Pattern.compile("([^a-zA-z0-9])");
//return escaper.matcher(str).replaceAll("\\\\$1");
return str.replaceAll("([^a-zA-Z0-9])", "\\\\$1");
}
}
Pattern.quote("blabla") works nicely.
The Pattern.quote() works nicely. It encloses the sentence with the characters "\Q" and "\E", and if it does escape "\Q" and "\E".
However, if you need to do a real regular expression escaping(or custom escaping), you can use this code:
String someText = "Some/s/wText*/,**";
System.out.println(someText.replaceAll("[-\\[\\]{}()*+?.,\\\\\\\\^$|#\\\\s]", "\\\\$0"));
This method returns: Some/\s/wText*/\,**
Code for example and tests:
String someText = "Some\\E/s/wText*/,**";
System.out.println("Pattern.quote: "+ Pattern.quote(someText));
System.out.println("Full escape: "+someText.replaceAll("[-\\[\\]{}()*+?.,\\\\\\\\^$|#\\\\s]", "\\\\$0"));
^(Negation) symbol is used to match something that is not in the character group.
This is the link to Regular Expressions
Here is the image info about negation:
I have a problem in getting the correct Regular expression.I have below xml as string
<user_input>
<UserInput Question="test Q?" Answer=<value>0</value><sam#testmail.com>"
</user_input>
Now I need to remove the xml character from Answer attribute only.
So I need the below:-
<user_input>
<UserInput Question="test Q?" Answer=value0value sam#testmail.com"
</user_input>
I have tried the below regex but did not worked out:-
str1.replaceAll("Answer=.*?<([^<]*)>", "$1");
its removing all the text before..
Can anyone help please?
You need to put ? within the first group to make it none greedy, also you dont need Answer=.*?:
str1.replaceAll("<([^<]*?)>", "$1")
DEMO
httpRequest.send("msg="+data+"&TC="+TC); try like this
Although variable width look-behinds are not supported in Java, you can work around it with .{0,1000} that should suffice.
Please check out this approach using 2 regexes, or 1 regex and 1 replace. Choose the one that suits best (I removed the \n line break from the first input string to show the flaw with using simple replace):
String input = "<user_input><UserInput Question=\"test Q?\" Answer=<value>0</value><sam#testmail.com>\"\n</user_input>";
String st = input.replace("><", " ").replaceAll("(?<=Answer=.{0,1000})[<>/]+(?=[^\"]*\")", "");
String st1 = input.replaceAll("(?<=Answer=.{0,1000})><(?=[^\"]*\")", " ").replaceAll("(?<=Answer=.{0,1000})[<>/]+(?=[^\"]*\")", "");
System.out.println(st + "\n" + st1);
Output of a sample program:
<user_input UserInput Question="test Q?" Answer=value0value sam#testmail.com"
</user_input>
<user_input><UserInput Question="test Q?" Answer=value0value sam#testmail.com"
</user_input>
First off, in your sample above, there is a trailing " after the email and > which I do not know if it was placed by error.
However, I will keep it there as according to your expected result, you need it to still be present.
This is my hack.
(Answer=)(<)(value)(>)(.+?([^<]*))(</)(value)(><)(.+?([^>]*))(>) to replace it with
$1$3$5$8 $10
The explanation...
(Answer=)(<)(value)(>) matches from Answer to the start of the value 0
(.+?([^<]*) matches the result from 0 or more right to the beginning < which starts the closing value tag
(</) here, I still select this since it was dropped in the previous expression
(><) I will later replace this with a space
(.+?([^>]*) This matches from the start of the email and excludes the > after the .com
(>) this one selects the last > which I will later drop when replacing.
The trailing " is not selected as I will rather not touch it as requested.
public class Format
{
public static void main(String args[])
{
System.out.printf("%30s|%30s","Organization","Number of users");
System.out.printf("%30s|%30s","Arcot","100");
}
}
It prints:
Organization| Number of users Arcot| 100
Why is the 2nd row out of alignment? The word "Arcot" is not given enough padding, although the word "100" is. I'm sorry, this text window applies its own formatting, it is not showing what I have pasted as the output. You may need to run the code to see the output obtained.
Try these.
System.out.println(String.format("%30s|%30s","Organization","Number of users"));
System.out.println(String.format("%30s|%30s","Arcot","100"));
System.out.printf("%30s|%30s\n","Organization","Number of users");
System.out.printf("%30s|%30s\n","Arcot","100");
You have to insert \n issue a newline character end of first parameter of printf.
More info about using escape character.
This works as expected:
System.out.printf("%30s|%30s%n","Organization","Number of users");
System.out.printf("%30s|%30s%n","Arcot","100");
results in
Organization| Number of users
Arcot| 100
on my machine. You didn't add line feeds. %n is the preferred notation in format Strings.