Adding a newline in TextView with String from database - android

I have an SQLite database where some of the values contain strings with the newline '\n' character. I was hoping that when that value was pulled from the database, put into a String and a TextView's setText() was set to the String value, the newlines would work, but unfortunately it does not. Any other options other than having to parse the string and break it up manually?

If you debug, you will see that the string is actually "\ \r\ \n" or "\ \n", ie, it is escaped. So if you massage that string, to get rid of the extra \, you will have your solution. This is true especially if you are reading from a database.

your string is being escaped when it is put into the database. You could try and unescape the string by calling String s = unescape(stringFromDatabase) before you place it in your TextView.
private String unescape(String description) {
return description.replaceAll("\\n", "\\n"); }
As a side note, make sure you are using DatabaseUtils.sqlEscapeString() on any kind of data that is from the user or an unknown changeable source when inserting data into the database. This will protect you from errors and SQL Injection.

Related

How to avoid nul value in URL in android?

I have a strange issue about using Retrofit2 in my android project. I got the issue about the server error since the request is something like that.
https://www.example.com/api/v1/skills?q=Good%00
Since the invalid value "%00" is not acceptable in our server, so it showed error on my activity.
API service
#GET("skills")
Observable<SearchItem> getSkills(#Query("q") String keyword);
In my fragment, I just get the text using following simple statement.
String keyword = editText.getText().toString()
api.getSkills(keyword);
What I want to know is the following:
Is it possible to have a word can be converted to "%00" ?
How to avoid this "Good%00" before I send to getSkills function?
To enable compile time checks on nullity add #NonNull annotation,
#GET("skills")
Observable<SearchItem> getSkills(#NonNull #Query("q") String keyword);
Another way is to change each "%00" in your string, using .replace()
Replace the string with "" if it contains %00
if (text.toString().contains("%00")){
text = text.replace("%00", "");
}
and then call getSkills(text) with updated value
Try this
Use trim()
The java string trim() method eliminates leading and trailing spaces. The unicode value of space character is '\u0020'. The trim() method in java string checks this unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.
SAMPLE CODE
String keyword = editText.getText().toString().trim();
api.getSkills(keyword)
or your can use
replace()
The java string replace() method returns a string replacing all the old char or CharSequence to new char or CharSequence.
SAMPLE CODE
url =url.replace("%00", "");
or You can use URLEncoder
Utility class for HTML form encoding. This class contains static methods for converting a String to the application/x-www-form-urlencoded MIME format. For more information about HTML form encoding
String encodedurl = URLEncoder.encode(yourURL,"UTF-8");
There is two way to solve this
1. you restrict the entry write below code
android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
you can add more thing which you want
String keyword = editText.getText().toString().replace("%00", "");
api.getSkills(keyword);

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

Escape sequence string processing in android

I have a string variable in my android ap which contains some url http://www.google.com. The string variable is declared as shown below:
String html="";
But there is an error saying that I have to put (semicolon); after the a href=". But actually I want the entire line content ie
(href="http://www.google.com") in the string variable. How can it be achieved?? Thanks in advance.
doubles quotes needs to escaped.
try below one
String html="<a href='http://www.google.com'></a>";
else
String html= "";
You need to escape every " with \ if you want to put it in one String.
For example:
String html="";
If you don't do this, compiler assumes, that you end this String after href= and tries to understand what http://www.google.com means in Java ;)

replaceAll function not working while removing special character

I am working with a project where some data are retrieved by JSON parsing. Unfortunately, invalid character '\' escapes. I need to remove them. I tried calling .replace("\\'","\");. This solution is not working. No exceptions are thrown, but the string does not change. Here is my code:
shop_name = c.getString(TAG_SHOP_NAME);
if(shop_name.contains("\\'")==true)
{
//try{
shop_name=shop_name.replaceAll(Pattern.quote("\\'"), "'");
Log.e("vvvvvv","new shop name: "+shop_name);}
//catch(Exception q){Log.e(TAG+" vvvv","EXPTN",q);}
}
send JSON object is: Bimal\'s
required object: Bimal's
Please let me know whether I went wrong somewhere or if there is any other method other than replaceAll.
You need to double escape the backslash as it's an escape character in both strings and regex:
shop_name.replaceAll("\\\\'", "'");
Or without using regex (as it's not needed in this circumstance):
shop_name.replace("\\'", "'");
Escape the meta character " with "\" :
string.replaceAll("\"", "");
Remember to assign it back to the String reference , because it returns a new String object.
You should use replace() instead:
str = str.replace("\"", "");
replaceAll() is used for replacing regular expressions.

New Line character \n not displaying properly in textView Android

I know that if you do something like
myTextView.setText("This is on first line \n This is on second line");
Then it will display properly like this:
This is on first line
This is on second line
When I store that string in a database and then set it to the view it displays as such:
This is on first line \n This is on second line
Here is the line of code I use to extract the string from the database:
factView.setText(factsCursor.getString(MyDBAdapter.FACT_COLUMN));
I simply populate the database from a text file where each line is a new entry into the table so a line would look like this "This is on first line \n This is on second line" and it is stored as text.
Is there a reason that it isn't displaying the \n characters properly? It must be something to do with the string being in the database. Any suggestions?
I found this question Austyn Mahoney's answer is correct but here's a little help:
private String unescape(String description) {
return description.replaceAll("\\\\n", "\\\n");
}
description being the string coming out of your SQLite DB
As Falmarri said in his comment, your string is being escaped when it is put into the database. You could try and unescape the string by calling String s = unescape(stringFromDatabase) before you place it in your TextView.
As a side note, make sure you are using DatabaseUtils.sqlEscapeString() on any kind of data that is from the user or an unknown changeable source when inserting data into the database. This will protect you from errors and SQL Injection.
Try \\n instead of \n. If it throws an exception than use newline keyword in place of \n....newline is one character, ascii 10; it's often entered in a string literal...and will serve your purpose....:)
"This is on first line"||x'0A'||"This is on second line"
The || concatenates strings and the x'0A' is an unescaped newline.
If you're inserting records you'll have to replace every newline with "||x'0A'||" (If your string is double quoted). This may seem clumsy compared to the other asnswers. However if your lines are in separate columns this also works in a select:
SELECT firstline||x'0A'||secondline FROM wherever;
I found this while having the same problem you are: http://www.mail-archive.com/sqlite-users#sqlite.org/msg43557.html
A text area can be in multi line or single line mode. When it is in single line mode newline characters '\n' will be treated as spaces. When in doubt, to switch multi line mode on you can use the following code:
setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
I had the problem that the same code did not work on honeycomb and on froyo, which seem to have different defaults. I am now also excluding the flag when I want to force a field to be single lined.
From the Android doc:
public static final int TYPE_TEXT_FLAG_MULTI_LINE Added in API level 3
Flag for TYPE_CLASS_TEXT: multiple lines of text can be entered into
the field. If this flag is not set, the text field will be
constrained to a single line. Constant Value: 131072 (0x00020000)
http://developer.android.com/reference/android/text/InputType.html#TYPE_TEXT_FLAG_MULTI_LINE
You have to set the flag before you populate the field.

Categories

Resources