JSON string to TextView newline - android

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"));

Related

Add new line character in remote config text

I'm doing Firebase RemoteConfig integration. In one of the scenarios, I need to break a text line, so I tried to use new line character (\n).
But this is not working, it is neither displaying as an extra character nor creating another line.
My solution is replace \n manually (assuming that in Firebase Console you put property for TITLE as "Title\nNewLine"):
FirebaseRemoteConfig.getInstance().getString(TITLE).replace("\\n", "\n")
Try using an uncommon character like two pipes || and then replacing every occurance of those with a newline after you do getString() in the code.
You can insert encoded text(with Base64) to Firebase panel.
After, decode the String from your Java class and use it.
Like
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, "UTF-8");
The trick (which actually works for all HTML tags supported on your target platform) is to wrap the String in a JSON Object on RemoteConfig, like so:
{
"text":"Your text with linebreaks...<br><br>...as well as <b>bold</b> and <i>italic</i> text.
}
On the target platform you then need to parse the JSON and convert it back to a simple string. On Android this looks like this:
// extract value from JSON
val text = JSONObject(remoteConfig.getString("remoteConfig_key")).getString("text")
// create Spanned and use it
view.text = HtmlCompat.fromHtml(text)
So what worked for me is to use "||" (or some other character combination you are confident will not be in the string) as the new line character. Then replace "||" with "\n". This string will then display properly for me.
For some reason sending "\n" in the string doesn't get recognized as expected but adding it manually on the receiving side seems to work.
To make the suggestion mentioned above, you can try this code(that can be generalized to "n" number of elements). Simply replace the sample text with yours with the same format and add the amount of elements
String text="#Elemento1#Elemento2#Elemento3#";
int cantElementos=3;
arrayElementosFinales= new String[cantElementos];
int posicionNum0=0;
int posicionNum1;
int posicionNum2;
for(int i=0;i<cantElementos;i++){
posicionNum1=text.indexOf("#",posicionNum0);
posicionNum2=text.indexOf("#", posicionNum1+1);
char [] m = new char[posicionNum2-posicionNum1-1];
text.getChars(posicionNum1+1, posicionNum2,m,0);
arrayElementosFinales[i]=String.valueOf(m);
posicionNum0=posicionNum2;
}
Use Cdata in the remote config in combination with "br" tag and HTML.fromHtml() .. for eg.
<![CDATA[ line 1<br/>line 2]]>

How to replace the characher `\n` as a new line in android

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 );

\n not breaking lines in Java

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.

How to add a line break in an Android TextView?

I am trying to add a line break in the TextView.
I tried suggested \n but that does nothing. Here is how I set my texts.
TextView txtSubTitle = (TextView)findViewById(r.id.txtSubTitle);
txtSubTitle.setText(Html.fromHtml(getResources().getString(R.string.sample_string)));
This is my String: <string name="sample_string">some test line 1 \n some test line 2</string>
It should show like so:
some test line 1
some test line 2
But it shows like so: some test line 1 some test line 2.
Am I missing something?
\n works for me, like this:
<TextView android:text="First line\nNext line"
ok figured it out:
<string name="sample_string"><![CDATA[some test line 1 <br />some test line 2]]></string>
so wrap in CDATA is necessary and breaks added inside as html tags
Android version 1.6 does not recognize \r\n.
Instead, use: System.getProperty("line.separator")
String s = "Line 1"
+ System.getProperty("line.separator")
+ "Line 2"
+ System.getProperty("line.separator");
Linebreaks (\n) only work if you put your string resource value in quotes like this:
<string name="sample_string">"some test line 1 \n some test line 2"</string>
It won't do linebreaks if you put it without quotes like this:
<string name="sample_string">some test line 1 \n some test line 2</string>
yes, it's that easy.
Tried all the above, did some research of my own resulting in the following solution for rendering linefeed escape chars:
string = string.replace("\\\n", System.getProperty("line.separator"));
Using the replace method you need to filter escaped linefeeds (e.g. '\\n')
Only then each instance of line feed '\n' escape chars gets rendered into the actual linefeed
For this example I used a Google Apps Scripting noSQL database (ScriptDb) with JSON formatted data.
Cheers :D
There are two ways around this.
If you use your string as a raw string, you need to use the newline
character. If you use it as html, e.g. by parsing it with Html.fromString,
the second variant is better.
1) Newline character \n
<string name="sample">This\nis a sample</string>
2) Html newline tag <br> or <br />
<string name="sample">This<br>is a sample</string>
This worked for me
android:text="First \n Second"
This worked for me, maybe someone will find out this helpful:
TextView textField = (TextView) findViewById(R.id.textview1);
textField.setText("First line of text" + System.getProperty("line.separator") + "Linija 2");
If you're using XML to declare your TextView use android:singleLine = "false" or in Java, use txtSubTitle.setSingleLine(false);
Used Android Studio 0.8.9. The only way worked for me is using \n.
Neither wrapping with CDATA nor <br> or <br /> worked.
I use the following:
YOUR_TEXTVIEW.setText("Got some text \n another line");
very easy : use "\n"
String aString1 = "abcd";
String aString2 = "1234";
mSomeTextView.setText(aString1 + "\n" + aString2);
\n corresponds to ASCII char 0xA, which is 'LF' or line feed
\r corresponds to ASCII char 0xD, which is 'CR' or carriage return
this dates back from the very first typewriters, where you could choose to do only a line feed (and type just a line lower), or a line feed + carriage return (which also moves to the beginning of a line)
on Android / java the \n corresponds to a carriage return + line feed, as you would otherwise just 'overwrite' the same line
As I know in the previous version of android studio uses separate lines " \n " code. But new one (4.1.2) uses "<br/" to separate lines. For example -
Old one:
<string name="string_name">Sample text 1 \n Sample text 2 </string>
New one:
<string name="string_name">Sample text 1 <br/> Sample text 2 </string>
Also you can add "<br/>" instead of \n.
It's HTML escaped code for <br/>
And then you can add text to TexView:
articleTextView.setText(Html.fromHtml(textForTextView));
Try to double-check your localizations.
Possible, you trying to edit one file (localization), but actually program using another, just like in my case. The default system language is russian, while I trying to edit english localization.
In my case, working solution is to use "\n" as line separator:
<string name="string_one">line one.
\nline two;
\nline three.</string>
You could also use the String-Editor of Android Studio, it automatically generates line brakes and stuff like that...
As Html.fromHtml deprecated I simply I used this code to get String2 in next line.
textView.setText(fromHtml("String1 <br/> String2"));
.
#SuppressWarnings("deprecation")
public static Spanned fromHtml(String html){
Spanned result;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
result = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);
} else {
result = Html.fromHtml(html);
}
return result;
}
The most easy way to do it is to go to values/strings (in your resource folder)
Declare a string there:
<string name="example_string">Line 1\Line2\Line n</string>
And in your specific xml file just call the string like
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/example_string" />
I found another method:
Is necessary to add the "android:maxWidth="40dp"" attribute.
Of course, it may not work perfectly, but it gives a line break.
\n was not working for me. I was able to fix the issue by changing the xml to text and building the textview text property like below.
android:text="Line 1
Line 2
Line 3
DoubleSpace"
Hopefully This helps those who have said that \n did not work for them.
I'm reading my text from a file, so I took a slightly different approach, since adding \n to the file resulted in \n appearing in the text.
final TextView textView = (TextView) findViewById(R.id.warm_up_view);
StringBuilder sb = new StringBuilder();
Scanner scanner = new Scanner(getResources().openRawResource(R.raw.warm_up_file));
while (scanner.hasNextLine()) {
sb.append(scanner.nextLine());
sb.append("\n");
}
textView.setText(sb.toString());
In my case, I solved this problem by adding the following:
android:inputType="textMultiLine"
Maybe you are able to put the lf into the text, but it doesn't display? Make sure you have enough height for the control. For example:
Correct:
android:layout_height="wrap_content"
May be wrong:
android:layout_height="10dp"
I feel like a more complete answer is needed to describe how this works more thoroughly.
Firstly, if you need advanced formatting, check the manual on how to use HTML in string resources.
Then you can use <br/>, etc. However, this requires setting the text using code.
If it's just plain text, there are many ways to escape a newline character (LF) in static string resources.
Enclosing the string in double quotes
The cleanest way is to enclose the string in double quotes.
This will make it so whitespace is interpreted exactly as it appears, not collapsed.
Then you can simply use newline normally in this method (don't use indentation).
<string name="str1">"Line 1.
Line 2.
Line 3."</string>
Note that some characters require special escaping in this mode (such as \").
The escape sequences below also work in quoted mode.
When using a single-line in XML to represent multi-line strings
The most elegant way to escape the newline in XML is with its code point (10 or 0xA in hex) by using its XML/HTML entity
or
. This is the XML way to escape any character.
However, this seems to work only in quoted mode.
Another method is to simply use \n, though it negatively affects legibility, in my opinion (since it's not a special escape sequence in XML, Android Studio doesn't highlight it).
<string name="str1">"Line 1.
Line 2.
Line 3."</string>
<string name="str1">"Line 1.\nLine 2.\nLine 3."</string>
<string name="str1">Line 1.\nLine 2.\nLine 3.</string>
Do not include a newline or any whitespace after any of these escape sequences, since that will be interpreted as extra space.
I would recommend querying the line.separator property, and using that whenever you want to add a line break.
Here is some sample code:
TextView calloutContent = new TextView(getApplicationContext());
calloutContent.setTextColor(Color.BLACK);
calloutContent.setSingleLine(false);
calloutContent.setLines(2);
calloutContent.setText(" line 1" + System.getProperty ("line.separator")+" line2" );

New Line character \n not displaying properly in textView Android

I know that if you do something like
myTextView.setText("This is on first line \n This is on second line");
Then it will display properly like this:
This is on first line
This is on second line
When I store that string in a database and then set it to the view it displays as such:
This is on first line \n This is on second line
Here is the line of code I use to extract the string from the database:
factView.setText(factsCursor.getString(MyDBAdapter.FACT_COLUMN));
I simply populate the database from a text file where each line is a new entry into the table so a line would look like this "This is on first line \n This is on second line" and it is stored as text.
Is there a reason that it isn't displaying the \n characters properly? It must be something to do with the string being in the database. Any suggestions?
I found this question Austyn Mahoney's answer is correct but here's a little help:
private String unescape(String description) {
return description.replaceAll("\\\\n", "\\\n");
}
description being the string coming out of your SQLite DB
As Falmarri said in his comment, your string is being escaped when it is put into the database. You could try and unescape the string by calling String s = unescape(stringFromDatabase) before you place it in your TextView.
As a side note, make sure you are using DatabaseUtils.sqlEscapeString() on any kind of data that is from the user or an unknown changeable source when inserting data into the database. This will protect you from errors and SQL Injection.
Try \\n instead of \n. If it throws an exception than use newline keyword in place of \n....newline is one character, ascii 10; it's often entered in a string literal...and will serve your purpose....:)
"This is on first line"||x'0A'||"This is on second line"
The || concatenates strings and the x'0A' is an unescaped newline.
If you're inserting records you'll have to replace every newline with "||x'0A'||" (If your string is double quoted). This may seem clumsy compared to the other asnswers. However if your lines are in separate columns this also works in a select:
SELECT firstline||x'0A'||secondline FROM wherever;
I found this while having the same problem you are: http://www.mail-archive.com/sqlite-users#sqlite.org/msg43557.html
A text area can be in multi line or single line mode. When it is in single line mode newline characters '\n' will be treated as spaces. When in doubt, to switch multi line mode on you can use the following code:
setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
I had the problem that the same code did not work on honeycomb and on froyo, which seem to have different defaults. I am now also excluding the flag when I want to force a field to be single lined.
From the Android doc:
public static final int TYPE_TEXT_FLAG_MULTI_LINE Added in API level 3
Flag for TYPE_CLASS_TEXT: multiple lines of text can be entered into
the field. If this flag is not set, the text field will be
constrained to a single line. Constant Value: 131072 (0x00020000)
http://developer.android.com/reference/android/text/InputType.html#TYPE_TEXT_FLAG_MULTI_LINE
You have to set the flag before you populate the field.

Categories

Resources