4

When I set a textView's string manually like below it works.

<TextView
         android:id="@+id/textView1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="line 1 \n line 2"/>

However, when I try to show a String on this textView it doesn't go to a new line.

String sample = "line 1 \n line 2";
textView1.setText(sample);

Note: Actually I am getting the String from a SQLite database. But that shouldn't make a difference right? Beacause it's still a String!

sample = cursor.getString(DBAdapter.COL_sample);
textView1.setText(sample);

So, now my TextView shows "\n" or "\r\n" character instead of a line break.

3 Answers3

4

Ah so now since you say it's from the SQLite database, that's the issue there.

You can refer to the answer by Blundell here.

The issue is that SQLite will escape your new line characters so when you retrieve it again, it will come out as \\\n or equivalent in which you will need to unescape to display properly (so remove the extra slash so it is just \n.

So depending on what new line characters are being saved into your database, you will need to handle accordingly.

So using the linked answer, you could do something like this (will depend on the number of backslashes and other characters you need to do):

textView1.setText(sample.replaceAll("\\\\n", "\n"));

If you need to do it in multiple places create a function for this.

Community
  • 1
  • 1
singularhum
  • 5,072
  • 2
  • 24
  • 32
2

You can try

sample = sample.replace("\\\n", System.getProperty("line.separator"));
Fareya
  • 1,523
  • 10
  • 11
1

It does work when you extract to the strings.xml file (you can quickly do this with the cmd + 1 button).

This is a fix, and you will be properly abstracting your strings as a bonus.

Booger
  • 18,579
  • 7
  • 55
  • 72
  • Sorry but I am a total newbie and I don't know what you're talking about. Can you provide more detailed instructions on how to solve this problem? – AspiringDeveloper Apr 20 '14 at 01:04
  • Highlight the string. Press cmd+1. Then select the extract String option for the ide to do this for you. You will understand after it is done. Check the res folder. – Booger Apr 20 '14 at 04:32