I post a string to a database and use this method to make sure it's URL safe:
public String URLsafe(String text){
try {
return URLEncoder.encode(text, "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("URL SAFE", text+" is not URL safe");
}
return "";
}
Thing is when I retrieve the String, characters like ' look like /'. Is there a way to 'decode' the String?
Have you tried URLDecoder.decode(encoded, "utf-8")? It's the corresponding 'opposite' method to the URLEncoder.encode method you're using.
https://developer.android.com/reference/java/net/URLDecoder.html
You can use the decode method:
UrlDecoder.decode(String s, String enc)
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm trying to get text from server and then check it a to know what actions to take with the text adopted. The problem is that when I try to check if the received text for example is "Exited" the query always return the value "false" when the received text is really "Exited".
Here is the code :
class Get_Message_From_Server implements Runnable
{
public void run()
{
InputStream iStream = null;
try
{
iStream = Duplex_Socket_Acceptor.getInputStream();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//Create byte array of size image
byte[] Reading_Buffer = null;
try
{
Reading_Buffer = new byte [Duplex_Socket_Acceptor.getReceiveBufferSize()];
//New_Buffer = new byte [100];
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] Byte_Char_1 = new byte[1];
int Byte_String_Lenght = 0;
//read size
try
{
iStream.read(Reading_Buffer);
String Reading_Buffer_Stream_Lenghtor = new String(Reading_Buffer);
//System.out.println("full : " + Reading_Buffer_Stream_Lenghtor);
Byte_String_Lenght = Reading_Buffer_Stream_Lenghtor.indexOf(new String(Byte_Char_1));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//Convert to String
Meassage = new String(Reading_Buffer);
Meassage = Meassage.substring(0, Byte_String_Lenght);//The text that received
Message_Getted = 1;
}
}
The query :
if(Message_1 != "Exited")//the message query
{
System.out.println("Continued 253");
continue;
}
Its always return the value - false
its important to know that the message is in Utf - 8 encoding
so how i can to fix the issue ?
If you compare strings by using oparators, Java will not look at the contents of the string but at the reference in memory. To compare String content in Java, you should use the following:
String Message_1; // Hopefully has a value sent by the server
if(Message_1.equals("Exited")) {
// Do stuff when exited
} else {
// Do stuff when not exited
}
String is a variable - and variables should start with lower Case letter - Please read Java Code conventions. Also to check if your message contains string you thing it should just do System.out.println(Message_1); and if the message contains what you expect you compare string doing
if(Message_1.equals("Exited")) {
System.out.println("Yes they are equal");
} else {
System.out.println("No they are not");
}
If this will print "No they are not" that simply means that your variable Message_1 is not what you think it is.. As simple as that. There is no such a thing as .equals method does not work. Its your variable that doesn't ;)
I have a database which is encoded with Base64. I am getting data from that DB and i use it in my android layouts, also i send data to the DB. When there is Cyrillic text, it seems that it is not encrypting it properly, because i already fixed the decoding, but it cannot recognise the cyrillic encrypted text. I am using standard function to encode it is working properly with Latin characters:
public String encrypt(String text){
String result;
result = Base64.encodeToString( text.getBytes(), Base64.NO_WRAP );
return result;}
I tried a few variations but nothing worked out. Do you know how to encrypt it correctly?
I found the answer myself:
String result = null;
try {
result = Base64.encodeToString( text.getBytes("Windows-1251"), Base64.NO_WRAP );
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thanks anyway :)
I'm relatively new to Android development and am writing my first REST-based app. I've opted to use the Android Asynchronous HTTP Client to make things a bit easier. I'm currently just running through the main "Recommended Usage" section on that link, essentially just creating a basic static HTTP client. I'm following the code given, but changing it around to refer to a different API. Here's the code in question:
public void getFactualResults() throws JSONException {
FactualRestClient.get("q=Coffee,Los Angeles", null, new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONArray venues) {
// Pull out the first restaurant from the returned search results
JSONObject firstVenue = venues.get(0);
String venueName = firstVenue.getString("name");
// Do something with the response
System.out.println(venueName);
}
});
}
The String venueName = firstVenue.getString("name"); line is currently throwing an error in Eclipse: "Type mismatch: cannot convert from Object to JSONObject". Why is this error occurring? I searched other threads which led me to try using getJSONObject(0) instead of get(0) but that led to further errors and Eclipse suggesting using try/catch. I haven't changed any of the code on the tutorial, save for the variable names and URL. Any thoughts/tips/advice?
Thanks so much.
EDIT:
Here is the onSuccess method, modified to include the try/catch blocks suggested. Eclipse now shows the "local variable may not have been initialized" for firstVenue here: venueName = firstVenue.getString("name"); and for venueName here: System.out.println(venueName); Even if I initialize String venueName; directly after JSONObject firstVenue; I still get the same error. Any help in resolving these would be greatly appreciated!
public void onSuccess(JSONArray venues) {
// Pull out the first restaurant from the returned search results
JSONObject firstVenue;
try {
firstVenue = venues.getJSONObject(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String venueName;
try {
venueName = firstVenue.getString("name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Do something with the response
System.out.println(venueName);
}
You can try to convert object you are getting from querying to String and then use
final JSONObject jsonObject = new JSONObject(stringresult);
I was getting same error earlier, it worked for me.
Yes, you should be using getJSONObject to ensure that the value you obtain is a JSON object. And yes, you should catch the possible JSONException which is thrown if that index in the array doesn't exist, or does not contain an object.
It'll look something like this:
JSONObject firstVenue;
try {
firstVenue = venues.get(0);
} catch (JSONException e) {
// error handling
}
convert obj to json Object:
Object obj = JSONValue.parse(inputParam);
JSONObject jsonObject = (JSONObject) obj;
The solution provided by Shail Adi only worked for me by setting the initial values of firstVenue and venueName to null. Here's my code:
JSONObject firstVenue = null;
try {
firstVenue = (JSONObject)venues.get(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String venueName = null;
try {
venueName = firstVenue.getString("name");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Do something with the response
System.out.println(venueName);
I'm trying to get the int value of a text file that have text like:
123456789 12345678 1234567 123456 12345 1234 123 12 1
as you can see every number is different and they are in a same line separated by a "space". I need to get the values separated. to get something like this:
INT1 = 123456789, INT2 = 12345678, INT3 = 1234567;
and so on. I don't create the text so I don't know how much numbers and groups they are, but they are always separated by a "space". I know how to read it. This is how I'm reading it:
try {
TEST1 = new BufferedReader(new FileReader("/sdcard/test.txt")).readLine();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TEST.setText(""+scaling_available_frequencies);
and I got this output
194208 776175 958253 767883 700246 243663 966618 345199 945363 459833
NOTE: This is just a test.txt that I created to see if it works. The current code will ask the user for entering path and file name.
Now how can I set them to a variable per group?
Thanks
This is one way to parse the String to an integer array:
public int[] toIntArray( String stringFromFile ){
String[] allStrings = stringFromFile.split( "\\s" );
int[] intArray = new int[allStrings.length];
for( int i = 0; i < allStrings.length; ++i ){
try{
intArray[i] = Integer.parseInt( allStrings[i] );
}catch( NumberFormatException e ){
// Do whatever you think is appropriated
intArray[i] = -1;
}
}
return intArray;
}
Hope this helps.
I believe readLine() get you String.
You will need to use the Split() method of String and pass in the regularExpression (whitespace).
then you will need to use Integer.parseInt( ) method and pass in every string to parse them into Integer.
you also need a loop to do the parse until nothing left
What is the best way to determine a file type in Android?
I want to check if the given file is an image, a music file, etc.
Include some mime.types files in your assets folder (for example from /etc/mime.types).
Include activation.jar (from JAF) in your build path.
Use something like this:
try {
MimetypesFileTypeMap mftm =
new MimetypesFileTypeMap(getAssets().open("mime.types"));
FileTypeMap.setDefaultFileTypeMap(mftm);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Then use FileDataSource.getContentType() to obtain file types.
public static String getMimeType(String fileUrl) {
String extension = MimeTypeMap.getFileExtensionFromUrl(fileUrl);
final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
return (mimeType != null) ? mimeType : "unknown";
}
A common way is by their extension only, or you can parse the header, but it should be too much slower and more complex for your apps.