How to insert a new line in strings in Android - android

I'm creating an android application and within it there is a button that will send some information in an email, and I don't want to have everything all in one paragraph.
Here's what my app is doing for the putExtra for the email's body:
I am the first part of the info being emailed. I am the second part. I am the third part.
Here's what I want it to do:
I am the first part of the info being emailed.
I am the second part.
I am the third part.
How would I put a new line into a string or with the putExtra method to accomplish that?

Try:
String str = "my string \n my other string";
When printed you will get:
my string
my other string

Try using System.getProperty("line.separator") to get a new line.

I would personally prefer using "\n". This just puts a line break in Linux or Android.
For example,
String str = "I am the first part of the info being emailed.\nI am the second part.\n\nI am the third part.";
Output
I am the first part of the info being emailed.
I am the second part.
I am the third part.
A more generalized way would be to use,
System.getProperty("line.separator")
For example,
String str = "I am the first part of the info being emailed." + System.getProperty("line.separator") + "I am the second part." + System.getProperty("line.separator") + System.getProperty("line.separator") + "I am the third part.";
brings the same output as above. Here, the static getProperty() method of the System class can be used to get the "line.seperator" for the particular OS.
But this is not necessary at all, as the OS here is fixed, that is, Android. So, calling a method every time is a heavy and unnecessary operation.
Moreover, this also increases your code length and makes it look kind of messy. A "\n" is sweet and simple.

I use <br> in a CDATA tag.
As an example, my strings.xml file contains an item like this:
<item><![CDATA[<b>My name is John</b><br>Nice to meet you]]></item>
and prints
My name is John
Nice to meet you

If you want to add line break at runtime into a String from same string you are deriving the value then this Kotlin code works for me:
str = "<br>"+str?.replace("," , "</br><br>")+"</br>"
value = HtmlCompat.fromHtml(${skill_et_1}",Html.FROM_HTML_MODE_LEGACY)
tv.text = value

Related

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

Android Return Line (\n) in String

In android, a String resource can be created in XML by using
<string name="name">data</string>
to create a new line, \n may be used. However, if the user personally inputs data into an EditText and includes a \n, the writing is saved to a String and when the writing is displayed again in a TextView the result would be something such as:
Line 1\nLine2
How come the \n doesn't apply to user written Strings?
The end goal for me is to be able to have the user type a \n into a String to make sure the String is displayed in multiple lines.
How would this be achieved? Thanks in advance!
Use this :
TextView view = your text view;
view.setSingleLine(false);
view.setText("first line" + "\n" + "second line" + "\n" + "third line");
How are you doing setText() in the textView.
Try this...
TextView view = your text view;
view.setSingleLine(false);
view.setText("first line\n"+"second line\n"+"third line");
with
System.getProperty("line.separator")
you get a String which results in a new line.
I would replace \n by this expression.
The text entered in an input field is used as an actual text. That means, when the user enters the Hello \n World and the code calls getText().toString(), what will actually be returned is: Hello \\n World that means, it's the actual slash symbol and not the "carriage return" symbol.
I don't believe android has any built-in API to give you the actual code typed by the user, that means, that you have to write that code yourself. If all you need is the \n as a carriage return it is simple:
getText().toString().replace("\\n", "\n");

\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.

in android application how to detect the occurence of substring in a text

I'm getting a text extracted from qrcode from my application, but as I am using zxing library its putting an extra DEMO at the end. How to remove it from there?
I was trying this but it does not work:
String aboutText = (Global.text).toString();
aboutText = aboutText.replace("DEMO", " ");
String.replace only takes chars as argument. Try String.replaceFirst(String, String) instead.
aboutText = aboutText.replaceFirst("DEMO", " ");
shout work. You can also take a look at replaceAll
Here you are: String. As for a newbie it will be quite helpful to learn more about strings in Java and the operations with them.

Categories

Resources