Java (Android) - can't detect first character of string? - android

Not sure if I've missed something really obvious. I know for sure that my String is as follows:
1This is a test message
I'm trying to detect whether the first character is '1', so here's some of my code:
//This outputs '1'
Toast noCmd = Toast.makeText(Play.this, decodedMessage.substring(0,1), Toast.LENGTH_SHORT);
noCmd.show();
if (decodedMessage.charAt(0) == 1) {
noCmd = Toast.makeText(Play.this, "This should show up", Toast.LENGTH_SHORT);
noCmd.show();
noCmd = Toast.makeText(Play.this, finalMessage + " from " + sender, Toast.LENGTH_SHORT);
noCmd.show();
}
if (decodedMessage.substring(0,1) == "1") {
noCmd = Toast.makeText(Play.this, "This should show up", Toast.LENGTH_SHORT);
noCmd.show();
noCmd = Toast.makeText(Play.this, finalMessage + " from " + sender, Toast.LENGTH_SHORT);
noCmd.show();
}
As you can see, I'm trying two methods to get the toasts inside the if statement to show up. Weirdly, when the code is run, only the top (unconditional) toast displays.
Any ideas?

For the first one, the char is '1'. What's currently happening in your code is that because you're comparing a char with an integer, the char is being converted to an int using its character code. For a 1, that comes out as 49, which is not equal to the integer 1. You need to compare the char you're retrieving from the String with the char representing a digit "1", and that means you need to write it as '1'.
For the second one, you need to use .equals() to test for String equality, rather than ==. If you take two String objects s and t that have the same content, then you still will find that s==t will come out as false, unless they happen to be pointing at the same bit of memory (i.e., they're the same instance). To check whether they have the same content, you check
s.equals(t)
rather than
s==t
So, in summary, make the first one
if (decodedMessage.charAt(0) == '1') {
//toast stuff
}
and the second one
if ("1".equals(decodedMessage.substring(0,1))) {
//toast stuff
}
The reason, by the way, for not writing
if (decodedMessage.substring(0,1).equals("1")) {
//toast stuff
}
instead is that if the String on which you call .equals() is null then you'll end up with a NullPointerException, which usually you want to avoid. Actually in this case it would be fine, because the substring() call won't return null, but in the general case if you want to test whether s and "something" are equal then you use
"something".equals(s)
rather than
s.equals("something")
just in case s is null.

1 is an integer with value 1. If you want the ASCII 1, use '1' in single quotes which has the integer value of 49.
For comparing strings, use equals() and not ==. See How do I compare strings in Java?

To compare strings you need to use equals method:
if("1".equals(decodedMessage.charAt(0))){
}

Related

Starts comparing from the first number, not the whole number in kotlin

Hello I need to compare 2 numbers and I used >, => but it doesn't compare whole number, it looks for the leftest(left) number and compare
for example the number is 92,236 and i want to compare it with 100,000, it says 92236 is bigger than 100,000 and it is because of the first number which is 9 and the first number of second number that is 1 so it says 100,000 is not bigger than 9236
here what I had done
class IncreaseMoneyFragment : Fragment() {
var decide = ""
val increaseEditText = mIncreaseMoneyBinding.increaseEdt.text.toString() (get value of edit text)
val currentPayment = it.payment (get loanPayment from database)
if (increaseEditText > currentPayment) {
Toast.makeText(activity, "more", Toast.LENGTH_SHORT).show()
val more = "بیشتر"
decide = more
} else {
Toast.makeText(activity, "less", Toast.LENGTH_SHORT).show()
val less = "کمتر"
decide = less
}
builder.setTitle(" مبلغ مورد نظر از مبلغ قسط وام $decide است. ادامه میدهید؟")
THANKS FOR HELPING ME :)
You are most likely comparing strings (text) and not numbers here. That's why it's using the alphabetical order instead of the integer order:
println("92236" > "100000") // true
println(92236 > 100000) // false
You probably want to convert your strings into integers instead:
if (increaseEditText.toInt() > currentPayment.toInt()) {
// ...
}
Note that toInt will crash if the strings are not actual numbers (for instance empty).
You can use toIntOrNull if you want more safety. It returns null if the string is not a number, so you can simply check for null and deal with this problem separately before comparing.

Android, Kotlin: Checking if an NdefMessage converted to a String is equal to another String

I am trying to check if a value read from an NFC tag is equal to a String. The value written in the tag is correctly extracted, but when I try to compare the value with another string, as in the second "if" statement, it will always enter the "else" block.
private fun processNdefMessages(ndefMessages: Array<NdefMessage?>) {
var msg = ""
for (curMsg in ndefMessages) {
if (curMsg != null) {
// get the text written in the tag
msg = String(curMsg.getRecords().get(0).getPayload())
}
}
textFromTag = msg
if (textFromTag.equals("enjacket1")) {
Toast.makeText(applicationContext, "jacket1", Toast.LENGTH_LONG).show()
} else {
Toast.makeText(applicationContext, "$textFromTag", Toast.LENGTH_LONG).show()
}
EDIT: Also, when I read the payload from the tag, it always starts with "en" and then the actual string. This is why I compare the textFromTag with "enjacket1". I tried to eliminate the first two charaacters, but nothing seems to make a change to it...
This is probably because there is an extra byte in front of the language en characters to specify the language length which is probably not printable.
As NFC text is encoded as:
language length (1 byte) + language (n bytes) + Text
So read the first byte and trim accordingly or quick hack trim the first 3 bytes off for english messages.
More details at https://stackoverflow.com/a/59515909/2373819

Determine if content in editText is a "." ONLY

I have written a calculator type app. My mates found that entering single decimal points only into the editText's makes the app crash. Decimal numbers and integers work fine, but I get a number format exception when .'s are entered.
I want to check if a single . has been placed in an editText, in order for me to display a toast telling the user to stop trying to crash the app.
My issue is that a . doesn't have a numerical value...
You can wrap it in a try/catch which should be done anyway when parsing text. So something like
try
{
int someInt = Integer.parseInt(et.getText().toString());
// other code
}
catch (NumberFormatException e)
{
// notify user with Toast, alert, etc...
}
This way it will protect against any number format exception and will make the code more reusable later on.
You can treat .1 as 0.1 by the following.
String text = et.getText().toString();
int len = text.length();
// Do noting if edit text just contains a "." without numbers
if(len==0 || (len==1 && text.charAt(0).equals(".")))
return;
if(text.charAt(0).equals(".") && text.length() > 1) {
text = "0" + text;
}
// Do your parsing and calculations

Display text with if statement

I have some if statements, I do not know how to show the result on the screen.
Below are 2 things I have tried. I know the system.out goes to the log.
if (Enter == "1") {
// tv.setText("This is the display 1");
System.out.println("The 1");
}
else if (Enter == "2") {
System.out.println("The 2");
}
What is Enter? If it is an instance of an object, use lowercase names, so that would be enter.
To answer the question, you're probably comparing Strings. You should use .equals instead of ==.
So:
String enter = "1"; //your variable
if(enter.equals("1")){
System.out.println("The 1");
}else if(enter.equals("2"){
System.out.println("The 2");
}
When comparing primitive data types (like int, char, boolean) you can use ==, !=, etc.
When comparing objects (like String, Car, etc) you need to use the .equals() method.
See also this page.
Edit
Use a Toast:
Toast.makeText(this, "The 1", Toast.LENGTH_SHORT).show();
See here.
Do it with a Toast instead.
A Toast is a popup-like element in Android displaying a short message for a predefined duration on screen.
String enter = "whatever value enter has";
int duration = Toast.LENGTH_SHORT;
Context context = getApplicationContext();
String message = "The Nothing";
if (enter.equals("1")) {
message = "The 1";
} else if (enter.equals("2")){
message = "The 2";
}
Toast messageToast = Toast.makeText(context, message, duration);
messageToast.show();

Compare two things doesn't work

I have a strange problem in my android app. I must compare two string which are equals. I tried this :
if (raspunsdata.equals(rok)) {
System.out.println("changed ");
} else
System.out.println("no change");
}
but I get always "no change". Before this I have System.out.println for both strings, and both of them have the same value.
I tried also (raspunsdata==rok) and raspunsdata.contentEquals(rok) but I have the same problem. Why? I cant understand this.,...please help...
You might have unwanted white spaces. Might need to use the trim function just to make sure.
if (raspunsdata.trim.equals(rok.trim())) {
System.out.println("changed ");
} else
System.out.println("no change");
}
Btw equals is the correct way to check whether the values are the same.
.equals - compares the values of both objects. If you have 2 Strings with the same characters sets .equals will return true;
== - compares if two objects references are equal.
For example:
String a = "lol";
String b = a;
a == b - will be true.
Try reading: http://www.devdaily.com/java/edu/qanda/pjqa00001.shtml

Categories

Resources