I have one server response for an API request as shown below.
Success! Your request has been sent.\n\nWe’ll inform you once it is done.
This message I need to show in a Snackbar. I need new line to be added in the place of \n in this response . I tried by using replaceAll like
String message = (serverResponse.getMessage()).replaceAll("\\n", System.getProperty("line.separator"));
but it is showing like this
Same message if I add in string.xml resource file and get using getString(R.string.message) then the \n is working properly. How can I get a new line from this response string?
I tried changing \n with other character like <new_line> from server response and it is working fine with replaceAll. Problem is only with \n in response message. Is there any way to parse \n?
What you need is
String message = serverResponse.getMessage().replaceAll("\\\\n", "\n");
Why four backslashes are needed?
Because in Java backslash \ is escape character. If you want to have single backslash literal inside Java string you have to escape it and use \\
But, replaceAll method expects regex expression, where again backslash is escape character so you need to escape it, too.
Basically, in above code Java string parser will first convert those four backslashes to two \\\\ -> \\ and then regex parser will interpret remaining two backslashes as single backslash literal.
I believe you should be able to accomplish by doing the following.
// Replace "\n" with "<br>"
String message = (serverResponse.getMessage()).replaceAll("\\n", "<br>");
// Now set SnackBar text using HTML
mSnackBar.setText(HTML.fromHTML(message))
By using HTML.fromtHTML(String) you should be able to keep any formatting, such as breaks, ASCII HTML characters (bullets, stars, ect.), coloring and/or bolding/italicizing! I use this quite often to format text in TextViews that I have displayed to users. Do not see why it wouldn't work with SnackBars!
The Support Design Library will force only 2 lines for the Snackbar. This correlates to around 80dp max size.
Your solution should work, and is correct. Try it out in a Toast for a quick test. It will work as your expect. Another test you can do is to get rid of one of the \n, then it will probably display correctly; however, there are a few other options you can do for. Again, these are just tests. Check below for some real solutions!
Solutions
Remove all the \n from the Snackbar text. This is probably the best solution as it will allow your design to remain as close to Material as possible. Highly Recommended
You can get the actual TextView from the Snackbar, and modify its max number of lines
View sbv = snackbar.getView();
TextView tv = (TextView) sbv.findViewById(android.support.design.R.id.snackbar_text);
tv.setMaxLines(5);
In XML, you can modify the attribute that affects the Design Library's Snackbar number of lines. Not Recommended at all. This name can change without notice and break your UI
<integer name="design_snackbar_text_max_lines">5</integer>
Edit
If you have access to modify the contents of the server response, then I Highly highly highly suggest that you modify the returned server response to be way more concise to the user. Your current message is not concise and takes the user longer than needed to read.
Change it to this..
Request sent! You will be informed shortly.
I would actually find a better work for Request if you can. For example, if they ordered pizza and sent a request, then you ould say Order sent! .... Also, you might need to modify shortly to be more accurate to what a user can expect. Shortly, to me, means I should expect something within the hour at the very latest.
Anyways, check out this documentation. It is higly recommended for writing styles on Android. https://www.google.com/design/spec/style/writing.html#writing-language
Source: Android Multiline Snackbar
Snackbar snackbar = Snackbar.make(ref_id, "Success! Your request has been sent.\n\nWe’ll inform you once it is done.",
Snackbar.LENGTH_LONG).setDuration(Snackbar.LENGTH_LONG);
View snackbarView = snackbar.getView();
TextView tv= (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);
tv.setMaxLines(3);
snackbar.show();
How about this, Jrd.
strings.xml :
<string name="br">\n</string>
snackbar :
"Your request has been sent.." + getResources().getString(R.string.br)
StringBuilder strAppend = new StringBuilder();
strAppend.append("\n");
String newString = oldString.replace("\n", strAppend);
Log.d(TAG, "new: " + newString );
Related
First of all, I have gone through questions similar to the problem I am facing and those solutions are not working for me.
I have a TextView field on my Android app which is supposed to display multiple paragraphs i.e multiple new lines. I am getting this string from a database present in my online server as a JSON.
The text contains \n in it and I am expecting it to create new lines once it is received by the app. But it displays the whole text without any breaks along with "\n" character.
Below is the text present in my database.
First line. \nSecond line. \nThird line.
JSON string received by me inside the app.
{
"server_response": [{
"news_expand": "First line. \\nSecond line. \\nThird line."
}]
}
Code to extract string from JSON. I have left out the code to get get JSONArray and JSONObject for simplicity.
na_expand = gna_jo.getString("news_expand");
String extracted from the JSON. Got this by printing the na_expand string.
First line. \nSecond line. \nThird line.
Code to display the text in the TextView. Note the below 'na_expand' is an SparseArray present in a different activity hence the 'get(position)' code.
art_expand.setText(na_expand.get(position));
Below is the text I get on the emulator.
First line. \nSecond line. \nThird line.
What am I doing wrong here?
I think you should replace \n with \n in your string before setting test to your textview same below
b= b.replaceAll("\\n","\n");
So I found a workaround to the problem. As I was not sure where the issue was happening with \n, I modified my text present in the database to have a symbol other than \n. For eg: ~
First line.~Second line.~Third line.
You can use a website like this - https://www.gillmeister-software.com/online-tools/text/remove-line-breaks.aspx to replace the line breaks with any symbol you want.
Next, I used the StringSplitter class to break the string received in JSON and then again join it together with \n.
String joined;
String expand_temp = na_expand.get(position);
TextUtils.StringSplitter splitter = new TextUtils.SimpleStringSplitter('~');
splitter.setString(expand_temp);
StringBuilder stringBuilder = new StringBuilder();
for (String s_temp : splitter) {
stringBuilder.append(s_temp + "\n");
}
joined = stringBuilder.toString().trim();
This worked! I used this string in setText.
art_expand.setText(joined);
Try below code
myTextView.setText(Html.fromHtml("yourString with additional html tags"));
It will resolve all the html tags accordingly and effects of the tags will be reflected as well.
NOte: For devices greater than Nougat use below code
myTextView.setText(Html.fromHtml("<h2>Title</h2><br><p>Description here</p>", Html.FROM_HTML_MODE_COMPACT));
Hope that helps
The \ character is an escape character in JSON. So, when you get \\n, it actually means \n, not the newline character, which should have been just \n. So what you see is an expected behaviour. The JSON you get should have ideally been:
{
"server_response": [{
"news_expand": "First line. \nSecond line. \nThird line."
}]
}
Get your server to respond properly, otherwise you'll have to strip the unnecessary \.
Do you haveandroid:singleLine="true" on your TextView? If yes it will ignore the \n and will place the text in a single line.
You can just add replaceAll("\\n","\n") when you set value to your art_expand EditText. It should be:
art_expand.setText(na_expand.get(position).replaceAll("\\n","\n"));
I have a sample message . I need to create a regular expression to validate using android pattern.
sample message :
ERR|any digit|any digit;
checking validation:
1.Starting fixed characters :ERR
separator character :|
digit after | character
Message termination ;
I have tried like this way:^{ERR}+{|}+\d+{|}+\d+{;}$
Am I right? Please help to solve my problem.
The corrected regex you gave would be ^(ERR)+(\\|)+\\d+(\\|)+\\d+;$. Brackets are used for grouping, not braces. Also, in regex, + is used to represent "one or more of the previous expression". So writing (ERR)+ means "one or more of the string 'ERR'", so strings like "ERRERR|123|456;" would be matched (same thing goes for the pipe characters) - this is not what you are trying to do, I assume.
Having said that, try this: "^ERR\\|\\d+\\|\\d+;$"
I use a google api to generate a QR code from some data. It should be represent a VCARD format.
I call this url.
When i read the QR code, i nicely got back all the information i added to the link, except one little error.
The line sperators not working.
I got back this in Java (Android):
BEGIN:VCARD\nVERSION:2.1\nFN:Adam Varhegyi\nN:Adam;Varhegyi\nEMAIL:somemai#address.com\nTEL:1234567\nINTERNET:;\n\nORG:Mycompanyname\nEND:VCARD
Instead of this: (\n = linebreaks)
BEGIN:VCARD\nVERSION:2.1
FN:Adam Varhegyi
N:Adam;Varhegyi
EMAIL:somemai#address.com
TEL:1234567
INTERNET:;
ORG:Mycompanyname
END:VCARD
I tryed to work it arround with using a Scanner like this:
Scanner sc = new Scanner(myVCardStringInputFromQrCode);
sc.useDelimiter("\n");
while(sc.hasNext()){
String str = sc.next();
Log.i("VCARD LINE: ", str);
}
And this method only gives back 1 line! It is also ignores the "\n" marks.
Edit:
I also tried to use System.getProperty("line.separator") , but no use.
Edit part 2:
if(myVCardStringInputFromQrCode.contains("\n")){
Log.i("Found linebreak", "TRUE");
}
else{
Log.i("Found linebreak", "FALSE");
}
This code gives me back "FALSE" - Java says it is not contains "\n" when i clearly see it is.
Anybody know whats happening here?
Edit part 3:
The correct answer was deleted for some reason so i cannot mark it as "answer".
The solution was "\\n" instead of "\n" and it is working.
you can use System.getProperty("line.separator")
The \n you are seeing is not an actual line break. It is an escaped line break (a backslash, followed by an "n" character).
Try replacing all occurrences of this with an actual line break. Note that you should use the \r\n newline sequence because this is the newline sequence that vCards are supposed to use according to the specs.
myVCardStringInputFromQrCode = myVCardStringInputFromQrCode.replace("\\n", "\r\n");
Remember to pass \\n into the first argument and not \n. You need two backslashes in order to get a literal backslash.
\r\n instead of \n always worked for me.
I am trying to print a text which is fetched from the server. What is the best way to escape all special characters and print safely?
Because the string which is fetched from the server is entered by user an stores it on database. So there is a possibility use <?php ?> , & etc which may cause errors. I have tried < > which solved this problem.
But when setText() the string to an EditText the string gets truncated after &
So I need a best solution in which the text entered by the user will save safely in the database and retrieve the multi-line string with special characters safely.
What is the best way to do this?
I think you should use StringBuilder instead of simply reading the text from XML.
Follow these steps :
1) For each new tag in XML (in startElement) , create a String builder
2) Append the text to same StringBuilder in reading from Character method.
3) At last, assign that StringBuider to some String at the End of the tag (in EndElement).
Hope this will give you some idea to solve the problem .
Try ...!!!
Anyways the problem solved by using URLDecode.decode() at the app and urldecode(),stripslashes() at the server side.
Dont know whether this is the perfect solution, but it worked for me.
I am getting the Special Character " ã " and a dash sign " - " in my Text Response originally and When I perform the setText() on that text it shows me " � " sign at both the Places in my Device and emulator.
I want to show what exactly I have in the response, I have no clue what I do to look like what it actually is. I have googled much and tried various stuff like UTF-8, ISO Encoding Standards and HTML.fromHTML and others, but all useless.
Does anyone have the answer for this.
Thanks
DavidBrown
You can save the character as an Object and then retrieve the object and set it in the textview.
you can replace these special character with their ascii code either at server side or at client side. see if this works