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 ;)
Is it possible to write a whole shared_preferences.xml at once?
I want to realize a kind of settings import/export, so i need to read and write the whole file without loosing the xml-tags.
Reading the file is easy, but when i write my values (using PrintWriter) the old values stored in memory overwrite them seconds later.
what can i do to prevent that without writing single values using preference editor.
Now I read it from a file designed like Android's own preferences.xml and write it successively in my own function like this:
public static void preferencesImport(String PreferenceFilepath) {
preferencesImportPreferenceFilepath = PreferenceFilepath;
try {
// Parsing
// see http://theopentutorials.com/tutorials/android/xml/android-simple-xml-dom-parser/
XMLParserHelper parser = new XMLParserHelper(); // reference to described XMLDOMParser helper class
BufferedInputStream stream;
try {
stream = new BufferedInputStream(new FileInputStream(preferencesImportPreferenceFilepath));
org.w3c.dom.Document doc = parser.getDocument(stream);
// string value
NodeList nodeListString = doc.getElementsByTagName("string");
for (int i = 0; i < nodeListString.getLength(); i++) {
Element eString = (Element) nodeListString.item(i);
Pref.setString(eString.getAttribute("name"), eString.getTextContent()); // Own getter/setter -> use Android's preference manager instead in similar way
}
// repeat code above for boolean, long, int, float values
stream.close();
} catch (IOException e1) {
// output IOException
} catch (Throwable t1) {
// output Throwable1
}
writer.close();
} catch (Throwable t2) {
// output Throwable2
}
}
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
As I know that Nokia and some others phone (like iPhone) are able to sent and receive class 0 SMS , is it possible for android ? Do Android have the API?
What is flash SMS?
Flash SMS is an SMS which is displayed on the phone screen immediately upon arrival.
Unless you choose to save the flash message, it will disappear upon navigating away and will not be saved in your inbox.
If several flash messages are sent to one phone, only the latest message will be displayed, and all the previous ones will be overwritten.
Class 0: Indicates that this message is to be displayed on the MS immediately and a message delivery report is to be sent back to the SC. The message does not have to be saved in the MS or on the SIM card (unless selected to do so by the mobile user).
For rooted Android it is possible to bypass an API and send Class 0 SMS. There is a project on Git Hub called ZeroSMS:
ZeroSMS is a proof-of-concept demonstrating a way to send Class 0 SMS on android >=2.3.
Note: this only works on versions 2.2 -> 4.1.2, the sendRawPdu method was removed, so you will need to find a new way to do this.
It was possible to send Flash SMS (that's the term for class 0 SMS) before Android 2.2.
Google removed the sendRawPdu API, so even if you used reflection, you wouldn't be able to do it.
Here's how I did it previously (this was tested on Android 1.6 and worked)
private void sendSms(String phone, String sms) {
if ((phone == null) || (sms == null) || (phone.length() == 0)
|| (sms.length() == 0)) {
String message = "Phone or message empty!!!";
Toast notification = Toast.makeText(getBaseContext(), message,
Toast.LENGTH_SHORT);
notification.show();
return;
}
// SecurityManager oldSM = System.getSecurityManager();
// MySecurityManager newSM = new MySecurityManager();
// System.setSecurityManager(newSM);
// ServiceManager.getService("isms")
// ServiceManager.getService("isms");
SmsManager m = SmsManager.getDefault();
PendingIntent sentIntent = PendingIntent
.getBroadcast(this, 0, new Intent(
MessageStatusReceiver_MESSAGE_STATUS_RECEIVED_ACTION),
0);
PendingIntent deliveryIntent = PendingIntent.getBroadcast(this, 0,
new Intent(SmsReceiverService_MESSAGE_SENT_ACTION), 0);
// String sms = "Message self-destroyed!!!";
// String phone = "93634096";
long NOW = System.currentTimeMillis();
String time = String.valueOf(NOW);
// // m.sendTextMessage(phone, null, sms, sentIntent, deliveryIntent);
// working // m.sendTextMessage(phone, null, sms, null, null);
byte[] bb = new byte[1];
Method m2 = null;
try {
m2 = SmsManager.class.getDeclaredMethod("sendRawPdu",
bb.getClass(), bb.getClass(), PendingIntent.class,
PendingIntent.class);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// send message
SmsMessage.SubmitPdu pdus = SmsMessage.getSubmitPdu(null, phone, sms,
false);
// http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;f=telephony/java/android/telephony/gsm/SmsMessage.java;h=9ccfa90d2e24e5caea26c1deac641b3c31ae56d4;hb=c883b143ba2b8bfe2f2033d00dee9ff733f1b59c
boolean submitted = false;
try {
byte[] encodedMessage = pdus.encodedMessage;
// byte[0] = mtiByte
// byte[1] = TP Message Reference
// byte[2] = length of source phone
// byte[3..length] = phone
// protocol identifier
int msgLen = encodedMessage[2] / 2;
// +2 -> length of source phone
// +2 -> for 91 after the length
// +1 -> TP PID
int indexTPDCS = msgLen + 5;
byte TPDCS = encodedMessage[indexTPDCS];
// System.out.println(TPDCS);
System.out.println(getHexString(encodedMessage));
byte[] changedMessage = encodedMessage.clone();
// Set bit 4 to 1 using OR (|), indicating there is a message class
// Set bit 0 and 1 to 0 using AND (&), indicating class 0
byte newTPDCS = (byte) ((TPDCS | 0x10) & 0xFC); // Flash SMS
changedMessage[indexTPDCS] = newTPDCS; // Class 0
System.out.println(getHexString(changedMessage));
// Log.d(SmsScheduler_TAG, getHexString(changedMessage));
boolean send = true;
if (send) {
m2.invoke(m, pdus.encodedScAddress, changedMessage, null, null);
// sendSMS(HexDump.bytesToHexString(pdus.encodedScAddress),
// HexDump.bytesToHexString(changedMessage), null);
String message = "Flash SMS sent to " + phone
+ " successfully!";
Toast notification = Toast.makeText(getBaseContext(), message,
Toast.LENGTH_SHORT);
notification.show();
Log.d(SmsScheduler_TAG, message);
submitted = true;
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// not essential, saves the SMS sent.
if (submitted) {
ContentValues values = new ContentValues();
values.put(ADDRESS, phone);
values.put(DATE, time);
values.put(READ, 0);
values.put(STATUS, -1);
values.put(TYPE, MESSAGE_TYPE_SENT);
values.put(BODY, sms);
Uri inserted = getContentResolver().insert(
Uri.parse("content://sms"), values);
}
// System.setSecurityManager(oldSM);
}
Scrool's answer is indeed correct, https://stackoverflow.com/a/12873325/3082310 , as ZeroSMS does send flash SMS's;
however, it is a Proof-of-Concept and only supports SMS's with 7-bit encoding.
For proper encoding it seems there is a need to modify the code and add if-then or switch-case statements:
For 7-bit coding, as in english
use (byte)0xF0
For 16-bit encoding, UCS-2 encoding
use (byte) 0x18
Otherwise, junk characters appear if you enter unsupported language.
Yes and no. Is it easily possible? No. Is it technically possible with tomfoolery (read: reflection)? Usually.
I want to translate my text into device language.
So I tried below code
String InputString="My text";
String OutputString = null;
Language fromLanguage = Language.ENGLISH;
Language toLanguage = Language.valueOf(Locale.getDefault().getDisplayLanguage().toUpperCase());
try {
Translate.setHttpReferrer("http://android-er.blogspot.com/");
OutputString = Translate.execute(InputString,
fromLanguage, toLanguage);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
OutputString = InputString;
}
return OutputString;
If device language is English it executes well but i changed to any other language then it shows
java.lang.IllegalArgumentException: FRANÇAIS is not a constant in the enum type class com.google.api.translate.Language
not FRANCAIS if I select any language except English it shows IllegalArgumentException with selected language.
What have I done wrong, or is there another way to translate text into device language?
Read this document, it explains all you need to know: Android Localization