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.
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 .txt file which contains above 1000 words
sample city names below
Razvilka
Moscow
Firozpur Jhirka
Kathmandu
Kiev
Pokhara
Merida
Delhi
Reshetnikovo
Ciudad Bolivar
Marfino
Zhukovskiy
Reutov
Kurovskoye
etc
I would like to have these words in this format below
"Razvilka","Moscow","etc","etc"
enclosed with double quotation and with a comma in the end.I am using Notepad++.Could you mention how to do it and which software should I use it?
If you're using Notepad++, make a Search and Replace replacing
\b(\w+)\b
with
"$1",
It'll find all words and replace with them self, surrounded by quotes. You'll have to manually remove the last , if that's unwanted.
Regards
I wonder if this question is about programming, but You tagged android, regex and android studio, so I guess it is. If yes, You can simply split a string in that way:
String[] splitted = yourString.split("\\s+");
In that case, You are splitting the strings by whitespaces (this regex is also for more than one whitespace), like Your string seems to be. If You have more than one delimiter, You can do it by using the OR operator |
String[]splitted = yourString.split("-|\\.");
In that example, You are splitting the String by - and . (minus and point). The delimiter is the sign where the String is splitted by.
I have declared a regex for password validation purposes in strings.xml file.
The criteria is
-should be atleast 8 characters
-should contain atleast one upper case letter
-should contain atleast one lower case letter
-should contain atleast one special character within these "##$%^+&="
So my whole regex looks like this now
^(?=.[0-9])(?=.[a-z])(?=.[A-Z])(?=.[##$%^+&=])(?=\S+$).{8,}$
But when I enter this, I get an error saying that & is
"Unescaped or non terminated character entity/reference"
So instead I used the escape sequence as & but the validation fails for &
I would b glad if anyone could help me out on this!!
Use * quantifers in the look-aheads. Right now, you check if 2nd character in the string meets your conditions. We need to test them all in the string.
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^+&=])(?=\S+$).{8,}$
Here is a demo.
EDIT
Since the regex is located inside the XML code, it should be properly encoded. Or, use it inside CDATA block.
Are you missing a parameter in your curly braces? The last bit "{8,}" seems off.
I am writing my data in a database and getting it in android to set it in a textview but when I write for example:
"hello,
how are you?"
which means each line on a row if the row in the phone completes I get an extra line space and I don't want this need to remove it how can I do that?
thanks.
EDIT:
how can I place a line space in an arabic database: I added \n didn't work "\n" didn't work '\n' didn't work!! any ideas?
even if the database wasn't arabic that didn't work so can I place the \n in the database in a way that the android program takes it as a line space?
Edit2
Is there any other method? other than the one that I've mentioned in my answer? thanks.
check to see if you insert to your DB with that extra line.
showing more code would help us understand whats causing your issue...
but if you want to brute force it you could always use substring() for each or your elements or
`String input = EditTextinput.getText().toString();
input = input.replace(" ", "");`
but like #Nitin Sethi said more code especially the entry to your DB would give us a better understanding of what's going on
so what I did is that I've added the word "line space" in my database and I added
in my android code:
String input = //here I take the cde from cursor;
input = input.replace("line space", "\n");
and it worked perfectly but is there another way?
I have several cases where my string in strings.xml is quite long and has multiple lines done with \n.
Editing however is quite annoying since it is a long line in Eclipse.
Is there a better way to edit this so it looks like it will be presented later in the textview, ie the line breaks as line breaks and the text in multiline edit mode?
Two possibilities:
1. Use the Source, Luke
XML allows literal newline characters in strings:
<string name="breakfast">eggs
and
spam</string>
You just have to edit the XML code instead of using the nifty Eclipse GUI
2. Use actual text files
Everything inside the assets directory is available as a input stream from the application code.
You can access those file input streams of assets with AssetManager.open(), a AssetManager instance with Resources.getAssets(), and… you know what, here’s the Java-typical enormously verbose code for such a simple task:
View view;
//before calling the following, get your main
//View from somewhere and assign it to "view"
String getAsset(String fileName) throws IOException {
AssetManager am = view.getContext().getResources().getAssets();
InputStream is = am.open(fileName, AssetManager.ACCESS_BUFFER);
return new Scanner(is).useDelimiter("\\Z").next();
}
the use of Scanner is obviously a shortcut m(
Sure, you could put newlines into the XML, but that won't give you line breaks. In strings.xml, as in all XML files, Newlines in string content are converted to spaces. Therefore, the declaration
<string name="breakfast">eggs
and
spam</string>
will be rendered as
eggs and spam
in a TextView. Fortunately, there's a simple way to have newlines in the source and in the output - use \n for your intended output newlines, and escape the real newlines in the source. The above declaration becomes
<string name="breakfast">eggs\n
and\n
spam</string>
which is rendered as
eggs
and
spam
For anyone looking for a working solution that allows the XML String content to have multiple lines for maintainability and render those multiple lines in TextView outputs, simply put a \n at the beginning of the new line... not at the end of the previous line. As already mentioned, one or more new lines in the XML resource content is converted to one single empty space. Leading, trailing and multiple empty spaces are ignored. The idea is to put that empty space at the end of the previous line and put the \n at the beginning of the next line of content. Here is an XML String example:
<string name="myString">
This is a sentence on line one.
\nThis is a sentence on line two.
\nThis is a partial sentence on line three of the XML
that will be continued on line four of the XML but will be rendered completely on line three of the TextView.
\n\nThis is a sentence on line five that skips an extra line.
</string>
This is rendered in the Text View as:
This is a sentence on line one.
This is a sentence on line two.
This is a partial sentence on line three of the XML that will be continued on line four of the XML but will be rendered completely on line three of the TextView.
This is a sentence on line five that skips an extra line.
You may easily use "" and write any word even from other languages with out error:
<string name="Hello">"Hello
world!
سلام
دنیا!"
</string>