简体   繁体   中英

Reading a new line in a string with \n

When building a string, you can create newlines like so:

"This is the first line \n\n And this is the second line";

So, when running this portion of code all works well on the Android Emulator:

TextView newsTextArea = (TextView) view.findViewById(R.id.newsTextView);
newsTextArea.setText("Hello \n\n Whats up");

However, I have downloaded and parsed JSON from a web service we have created, and I have stored what I want in a variable like so:

GlobalSettings globalSettings = new GlobalSettings();
String newsText = globalSettings.getNews();

So the variable newsText equals a string, which lets say for arguments sake here is "Hello, this has two lines. \\n\\n Welcome to the test" .

When I run the above TextView code like this, it outputs it with the \\n\\n as literal characters.

newsTextArea.setText(newsText);

How can it be done so that the variable newsText keeps the formatting?

im a good guesser..lol well there may be soo many reasons that i think

1. newsTextArea.setSingleLine(false);
2. newsTextArea.setMinLines(2); or newsTextArea.setMaxLines(50);//any figure
3. String newsText = globalSettings.getNews().replace("\\\n", System.getProperty("line.separator"));
4. String newsText = globalSettings.getNews().toString();

play with these methods and see if one works for ya or two lol

However, I have downloaded and parsed JSON from a web service we have created ...

There are great chances that your JSON WS returns the literate sequence \\n as its output. Not the line-feed character ( <LF> ) as you expected it.

At this point you probably have two options:

  • Fix the web service to return the proper value
  • Change your client program to "patch" the faulty data in order to obtain the desired behavior. As of myself, I won't push toward that direction as it will soon become a maintenance nightmare (as soon as legitimate \\ will pop out in your data).

Maybe it is time to post an other question, this time about your JSON web service ?

It is likely that wherever that text comes from in the first place, the backslash is getting escaped. For example, it may be coming from a hard-coded constant in your service, entered into a form by a human and then validated, or etc.

Look at your JSON in its raw format before it is parsed. The JSON spec says that a single backslash followed by n means the newline character. If it looks like ["Hello, this has two lines. \\n\\n Welcome to the test"] then you should be good, because the JSON parser should interpret the newline characters correctly. However, if it looks like this: ["Hello, this has two lines. \\\\n\\\\n Welcome to the test"] , then the backslash character is being escaped, not the n.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM