Trouble Removing Whitespace in URL (Android Studio) - android

So I have a for loop that retrieves a room name to add to my baseurl, and so my URL will be this:
a = (baseUrl + roomName + "/users");
It works for all the rooms except one, which has a space, so I tried using this:
a.replaceAll("\\s+", "");
and other attemps but they return this
System.err﹕ java.io.FileNotFoundException: https://example.com:8443/conferenceRoom/First Floor/users
System.err﹕ at http.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)
Basically, I have a link like https://example.com:8443/conferenceRoom/First Floor/users
and I want it to be https://example.com:8443/conferenceRoom/FirstFloor/users so no space between 'first' and 'floor'
(note I do use openURLConnection(a) ) when actually using the URL later but I don't think it has anything to pertain to my problem, just wanted to clarify that a is a string

If you want to remove whitespaces from your url you can use trim() as
a= a.trim();
If you want to replace whitespaces with "%20" then you can use
a = a.replace(" ", "%20");
Having spaces in URLs can cause problems in certain situations. Therefore, a lot of the time spaces are replaced with %20 (which is the ascii encoded value for a space in a URL string). If you remove spaces from your URLs, you won't have the %20s. Otherwise, they're going to stick around.

Your url might contain UTF whitespaces which are not covered by the \s mofidier.
Just use trim which removes all whitespaces:
a = a.trim();

Related

URL encoding is getting failed for special character. #Android

I'm working on a solution where need to encode string into utf-8 format, this string nothing but device name that I'm reading using BluetoothAdapter.getDefaultAdapter().name.
For one of sampple I got a string like ABC-& and encoding this returned ABC-%EF%BC%86 instead of ABC-%26. It was weird until further debugging which helped to identify that there is difference between & and &. Second one is some other character which is failing to encoded as expected.
& and & both are different.
For encoding tried both URLEncoder.encode(input, "utf-8") and Uri.encode(input, "utf-8") but nothing worked.
This is just an example, there might be other character which may look like same as actual character but failed to encode. Now question are:
Why this difference, after all it is reading of some data from device using standard SDK API.
How can fix this be fixed. Find and replace with actual character could be a approach but scope is limited, there might be other unknown character.
Any suggestion around !!
One solution would be to define your allowed character scope. Then either replace or remove the characters that fall outside of this scope.
Given the following regex:
[a-zA-Z0-9 -+&#]
You could then either do:
input.replaceAll("[a-zA-Z0-9 -+&#]", "_");
...or if you don't care about possibly empty results:
input.replaceAll("[a-zA-Z0-9 -+&#]", "");
The first approach would give you a length-consistent representation of the original Bluetooth device name.
Either way, this approach has worked wonders for me and my colleagues. Hope this could be of any help 😊.

Add new line character in remote config text

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

IllegalArgumentException IN ANDROID URL

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");

what is the equivalent of "-" in an url?

How to change - in url.
I have got the same problem with space so i changed it with %20 and it worked:
name = name.replaceAll(" ","%20");
What is the equivalent of "-" in an url?
I tried %2C and it doesn't word: %2C -> ","
Use URLEncoder.encode(String s) to encode all your strings that you are gonna use for urls.
As far as I know the dash char is considered a safe char in the URL. If you have problems, then the problems might have nothing to do with the dash. Try, though, to replace it with %2D.
It's the ascii code (translator). - translates to %2d. You were close :)

Simple way to convert a URL into a filename

I'm writing an asynchronous image downloader for Android and was just wondering, given an arbitary URL such as:
http://www.android.com/images/brand/droid.gif
What would be the best way to convert the unique url to a filename. I thought about simply splitting the url and grabbing the last section, but I want the filename to be representative of the whole URL. The other alternatives I thought were replacing all the forward slashes with underscores or simply hashing the whole URL and storing this.
If anyone has any ideas I'd love to hear them!
Thanks
In case, usually uses MD5 hash. but I suggest to use 'aquery' library. In library you can simply download Image asynchronous and put it to view. It also support disk cache, memory cache simply.
This method will be fulfill your requirements. It will generate a name which will represent original URL. You can call generateNameFromUrl(String url) method like this.
String url = "http://www.android.com/images/brand/droid.gif";
String uniqueName = generateNameFromUrl(url));
Method is given below:
public static String generateNameFromUrl(String url){
// Replace useless chareacters with UNDERSCORE
String uniqueName = url.replace("://", "_").replace(".", "_").replace("/", "_");
// Replace last UNDERSCORE with a DOT
uniqueName = uniqueName.substring(0,uniqueName.lastIndexOf('_'))
+"."+uniqueName.substring(uniqueName.lastIndexOf('_')+1,uniqueName.length());
return uniqueName;
}
Input: "http://www.android.com/images/brand/droid.gif"
Output: "http_www_android_com_images_brand_droid.gif"

Categories

Resources