Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert a line break in a String to show on an Android TextView widget?

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.

like image 992
AspiringDeveloper Avatar asked Mar 20 '23 20:03

AspiringDeveloper


2 Answers

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.

like image 177
singularhum Avatar answered Mar 23 '23 00:03

singularhum


You can try

sample = sample.replace("\\\n", System.getProperty("line.separator"));
like image 20
Fareya Avatar answered Mar 22 '23 23:03

Fareya