Android removing newline characters - android

TextUtils.StringSplitter splitter = new TextUtils.SimpleStringSplitter('\n');
splitter.setString(tweetMessage);
tweetMessage = "";
for (String s : splitter)
{
Log.v(getClass().getSimpleName(), "Spliter :: "+ s);
tweetMessage +=s;
}
But this shows up the newline characters as Squares how do I get Rid of that

The characters you're seeing as squares probably aren't '\n' ('\u000A') characters.
If you're seeing a multiple lines in your output then it's possible that multiple characters are being used to split the lines. It might be '\r\n' but it could be something else.
Your best bet is to use a debugger to check exactly what the String contains before you split it. Or you could add some debug code like so:
for (int u : tweetMessage.toCharArray()) {
Log.v(getClass().getSimpleName(), String.format("\\u%04X",u));
}
If you see \u000D \u000A then your lines are separated by "\r\n". This means you can't use a SimpleStringSplitter to split the string since that will only split on a single character.
If you don't want to parse the string manually, you could use the String.split() method:
for (String s : tweetMessage.split("\r\n") {
//do something with s
}

If you need to remove newline/tab characters at the beginning and the end of a string (not the ones in the middle of the string) just use .trim() function to do the tric. This will remove white spaces from the begging and the end of the string.
Ex:
String xmlVersionDate = rootNode.getChildNodeWithName("last-updated").getValue().trim();

Related

android: divide string with punctuation and maintain punctuation with sentence in array

I have a sentence,
hello, What you are doing?How are you?
I wanted to split the sentence with characters such as .,?
I have achieved it using split function
and the output is:
arr[0]=hello
arr[1]=What you are doing
arr[2]=How are you
but I want the array as
arr[0]=hello
arr[1]=,
arr[2]=What you are doing
arr[3]=?
arr[4]=How are you
arr[5]=?
I have done this code
String text = "hello, What you are doing?How are you?";
String[] arr= text.split("[\\.,!;?:\"]+");
for (String str : arr) {
System.out.println(str);
}
Please help.
The general strategy to preserve text while also splitting on it at the same time is to use lookarounds. Lookarounds assert logic, but do not actually consume any text. They are basically zero width. I split below using the pattern:
(?=[\\.,!;?:\"])|(?<=[\\.,!;?:\"])
This says to split if we lookahead or lookbehind and see a punctuation character.
String sentence = "hello, What you are doing?How are you?";
String[] parts = sentence.split("(?=[\\.,!;?:\"])|(?<=[\\.,!;?:\"])");
for (String part : parts) {
System.out.println(part);
}
hello
,
What you are doing
?
How are you
?
Demo
You might also want to run String#trim on each term to get the exact output you want.

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]]>

JSON string to TextView newline

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

is it possible to cut text from string like this?

I want to put extra value from intent to other intent. But in other intent, app get all value. Example:
mAddress.setText(" from " + address);
String put_address = mAddress.getText().toString();
editIntent.putExtra("put_address", put_address);
is it possible to cut text "from" and get only address variable ???
you can split a string like
str = "From address#dd.com";
String modified = str.replace;
now splitstr contain your split strings
splitStr[1] contains "address#dd.com"
Can also use
str.substring(str.indexOf(" ")+1);
By the way, you can use jagapathi's answer. In his example he uses regular expression.
Regular expressions can help to parse, find, cut substrings using a particular pattern. In his code he splits string by any space character.
But, imho, the simplest solution is to create a substring using this code:
'put_address.substring(7);'
use one of these solutions:
String input = put_address.trim().substring(5);
*** note: 5 is index of real address first character;
String input = put_address..split(" ")[1];

How can I use Split method to find special characters and replace with images in android

I want to use split method to find special characters and then remove them and replace with images. I used html formatted texts in CDATA tag in Strings.xml file and send it to a Textview . How can I determine that special characters in that text (html formatted) in my java code and replace images and show those images between texts.
Thanks.
The simplest way would be to search within the String using the indexOf method. Something like this:
String yourString = "lorem(ipsum)";
String [] charsToReplace = new Array ('(', ')');
for (String thisChar : charsToReplace) {
while (yourString.indexOf(thisChar) > -1) {
// do something with ImageSpan or something
}
}
Not sure if this is the best way though...

Categories

Resources