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);
Related
I'm doing Firebase RemoteConfig integration. In one of the scenarios, I need to break a text line, so I tried to use new line character (\n).
But this is not working, it is neither displaying as an extra character nor creating another line.
My solution is replace \n manually (assuming that in Firebase Console you put property for TITLE as "Title\nNewLine"):
FirebaseRemoteConfig.getInstance().getString(TITLE).replace("\\n", "\n")
Try using an uncommon character like two pipes || and then replacing every occurance of those with a newline after you do getString() in the code.
You can insert encoded text(with Base64) to Firebase panel.
After, decode the String from your Java class and use it.
Like
byte[] data = Base64.decode(base64, Base64.DEFAULT);
String text = new String(data, "UTF-8");
The trick (which actually works for all HTML tags supported on your target platform) is to wrap the String in a JSON Object on RemoteConfig, like so:
{
"text":"Your text with linebreaks...<br><br>...as well as <b>bold</b> and <i>italic</i> text.
}
On the target platform you then need to parse the JSON and convert it back to a simple string. On Android this looks like this:
// extract value from JSON
val text = JSONObject(remoteConfig.getString("remoteConfig_key")).getString("text")
// create Spanned and use it
view.text = HtmlCompat.fromHtml(text)
So what worked for me is to use "||" (or some other character combination you are confident will not be in the string) as the new line character. Then replace "||" with "\n". This string will then display properly for me.
For some reason sending "\n" in the string doesn't get recognized as expected but adding it manually on the receiving side seems to work.
To make the suggestion mentioned above, you can try this code(that can be generalized to "n" number of elements). Simply replace the sample text with yours with the same format and add the amount of elements
String text="#Elemento1#Elemento2#Elemento3#";
int cantElementos=3;
arrayElementosFinales= new String[cantElementos];
int posicionNum0=0;
int posicionNum1;
int posicionNum2;
for(int i=0;i<cantElementos;i++){
posicionNum1=text.indexOf("#",posicionNum0);
posicionNum2=text.indexOf("#", posicionNum1+1);
char [] m = new char[posicionNum2-posicionNum1-1];
text.getChars(posicionNum1+1, posicionNum2,m,0);
arrayElementosFinales[i]=String.valueOf(m);
posicionNum0=posicionNum2;
}
Use Cdata in the remote config in combination with "br" tag and HTML.fromHtml() .. for eg.
<![CDATA[ line 1<br/>line 2]]>
Using the below url I got an error:
java.lang.IllegalArgumentException: Illegal character in path at index 47: http://safetracker-threetinker.rhcloud.com/api/{userid}/locations?lat={latitude}&lng={longitude}.
URL:
URL=http://safetracker-threetinker.rhcloud.com/api/{userid}/locations?lat={latitude}&lng={longitude}
how to solve the error. I don't have good knowledge in URL encoding. please help me to find the solution.
The problem is actually it is looking for long/integer value and you are passing a { just put a $ so that it will be replaced by the actual value pointed by the variable
http://safetracker-threetinker.rhcloud.com/api/1/locations?lat=5&lng=5
your Address is like this
URL=http://safetracker-threetinker.rhcloud.com/api/{userid}/locations?lat={latitude}&lng={longitude}
it should be like this
URL=http://safetracker-threetinker.rhcloud.com/api/${userid}/locations?lat=${latitude}&lng={longitude}
We can not use some special characters in URL, so we have to replace these special characters with its encoded form.
Replace your URL with following URL
URL=http://safetracker-threetinker.rhcloud.com/api/%7Buserid%7D/locations?lat=%7Blatitude%7D&lng=%7Blongitude%7D
May this help you.
URLEncoder should be the way to go. You only need to keep in mind to encode only the individual query string parameter name and/or value, not the entire URL, for sure not the query string parameter separator character & nor the parameter name-value separator character =.
String q = "replace_with user_id/locations?lat=replace with latitude&lng=replace with longitude";
String url = "http://safetracker-threetinker.rhcloud.com/api/=" + URLEncoder.encode(q, "UTF-8");
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 ;)
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.
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.