"if" not working properly - android

hey,
i'm new to android and i have a problem. here is my code:
Log.v("Test", "" + lv_arr_id[0]); //displays 0
if (lv_arr_id[0] == "0") {
Toast.makeText(longOperationContext, "A", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(longOperationContext, "B", Toast.LENGTH_SHORT).show();
}
lv_arr_id[0] has the value "0" and is a string, its external data pulled via json from web. however each time the B toast gets triggered instead of the A toast. the value really is 0, i tested this in the logcat.
any ideas why?
thanks in advance

== compares the object and not the String contents. Use .equals("0") instead.

It's not that if is not working properly.
In Java, you can't use == to compare objects of java.lang.String class. You need to use equals method.
Something like:
if (lv_arr[0].equals("0")) {
//
} else {
}

Related

My activity doesnt recognise text equality

Can someone help me, I'm killing myself over here. So in my activity I have this code and the application constantly displays that CurrentQ is not equal (currentQ.getODG() != answer.getText()) to the answer
I can see through LogCat with Log.d that the words are identical. I just can't understand what am I doing wrong.
08-25 05:28:45.125: D/yourans(25316): na život u mraku na život u mraku
this is from log cat
RadioGroup grp = (RadioGroup) findViewById(R.id.radioGroup1);
answer = (RadioButton) findViewById(grp.getCheckedRadioButtonId());
Log.d("yourans", currentQ.getODG() + " " + answer.getText());
if (currentQ.getODG().equals(answer.getText())) {
answer.setBackgroundResource(R.drawable.radiotocan);
Toast poruka1 = Toast.makeText(getApplicationContext(), "Točno!",
Toast.LENGTH_LONG);
View vieew1 = poruka1.getView();
// vieew.setBackgroundColor(Color.parseColor("#BD8BDC"));
vieew1.setBackgroundResource(R.drawable.toast1);
poruka1.setView(vieew1);
poruka1.setGravity(Gravity.CENTER_HORIZONTAL, 1, 1);
poruka1.show();
score1++;
Log.d("score1", "Your score" + score1);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
answer.setBackgroundResource(R.drawable.radiomain);
}
}, 300);
}
else if (currentQ.getODG() != answer.getText()) {
answer.setBackgroundResource(R.drawable.radionetocan);
Toast poruka2 = Toast.makeText(getApplicationContext(),
"Netočno, točan odgovor je:" + currentQ.getODG(),
Toast.LENGTH_LONG);
View vieew2 = poruka2.getView();
// vieew.setBackgroundColor(Color.parseColor("#BD8BDC"));
vieew2.setBackgroundResource(R.drawable.toast);
poruka2.setView(vieew2);
poruka2.setGravity(Gravity.CENTER_HORIZONTAL, 1, 1);
poruka2.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
answer.setBackgroundResource(R.drawable.radiomain);
}
}, 300);
}
Try
if(currentQ.getODG().equalsIgnoreCase(answer.getText()))
instead of
if(currentQ.getODG()!=answer.getText())
Hope it helps!
Java uses the double-equals sign to check to see if the objects the two variables point to are the same object, not whether they are equivalent. Since both Strings are each returned by two separate method calls, they will never be the same object.
Instead you'll want to use one of the equality-testing methods from the String class:
.equals(String b) Tests to see if the two strings are exactly the same.
.equalsIgnoreCase(String b) Tests to see if the two strings are the same, ignoring whether they're uppercase or lowercase.
There are more options you can find in the String class's documentation, just check the public methods list.
In your case, change this line:
else if (currentQ.getODG() != answer.getText()) {
To read like:
else if (!currentQ.getODG().equals(answer.getText())) {
But for more flexibility in recognizing answers, use .equalsIgnoreCase() like this:
else if (!currentQ.getODG().equalsIgnoreCase(answer.getText())) {
try this:
change:
currentQ.getODG().equals(answer.getText())
to:
currentQ.getODG().trim().equalsIgnoreCase(answer.getText().trim())
change:
else if (currentQ.getODG() != answer.getText())
to:
else
I think probably there's blank space in your string, so use trim() to cut them out, then compare the strings while ignoring capital letter.
FYI: Reference.

Comparing two EditText values in android

I'm trying to make an app where the user enters a word into an EditText box. Then, they enter something into another box and it checks to see if they are the same word. Here's the code that I used:
String word = textfield1.getText().toString();
String answer = textfield2.getText().toString();
textfield2.setText(textfield2.getText().toString());
if(word == answer){
Toast.makeText(getApplicationContext(), "correct",
Toast.LENGTH_LONG).show();
}else
Toast.makeText(getApplicationContext(), "incorrect", Toast.LENGTH_LONG).show();
}
However, it always says that the two strings aren't the same even if they are. Is there a way to fix this?
You can't compare strings with the == operator.
Use .equals() instead:
if(word.equals(answer)) {
//do whatever
}
Use String.equalsIgnoreCase for comparing content of both string variables.:
if(word.equalsIgnoreCase(answer)){
}
Use:
String word = textfield1.getText().toString();
String answer = textfield2.getText().toString();
if(answer.contentEquals(word)){
// Do something if equals
}
else{
// Do something if not equals
}
I think the best way to do this is using TextUtils:
if(TextUtils.equals(textfield1.getText(),textfield2.getText())){
//do something
}
instead of
if(word.contentEquals(answer)){
}
Use
if(word.equals(answer))
as we cant compare strings with Equal to (==) operator
Try This::
String word = textfield1.getText().toString();
String answer = textfield2.getText().toString();
if(word.equals(answer)){
Toast.makeText(getApplicationContext(), "correct",
Toast.LENGTH_LONG).show();
}else
Toast.makeText(getApplicationContext(), "incorrect", Toast.LENGTH_LONG).show();
}

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

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))){
}

IfElse or regex

Which one of these would be the best way to do this when you have very long IfElse?
if (text.contains("text"))
{
// do the thing
}
else if (text.contains("foo"))
{
// do the thing
}
else if (text.contains("bar"))
{
// do the thing
}else ...
Or
if (text.contains("text") || text.contains("foo") || ...)
{
// do the thing
}
Or maybe
Pattern pattern = Pattern.compile("(text)|(foo)|(bar)|...");
Matcher matcher = pattern.matcher(text);
if(matcher.find())
{
// do the thing
}
And I mean ONLY when you have to check a lot of these. Thanks!
I would personally use a set as I think it is easier to read and the contains will be efficient in O(1):
Set<String> keywords = new HashSet<String>();
keywords.add("text");
keywords.add("foo");
keywords.add("bar");
if(keywords.contains(text)) {
//do your thing
}
And if you like it compact, you can also write:
Set<String> keywords = new HashSet<String>(Arrays.asList("text", "foo", "bar"));
if(keywords.contains(text)) {
//do your thing
}
And finally, if you always use the same list, you can make keywords private static final instead of recreating it each time you run the method.
EDIT
Following a comment, it is true that what is above is equivalent to using a condition with text.equals("xxx"), not text.contains("xxx"). If you really meant to use contains, then you would have to iterate over the set and test each string, but it becomes an O(n) operation:
for (String key : keywords) {
if (text.contains(key)) {
//do your stuff
break;
}
}
Usually long If else statements are replaced with case statements, but this is not always possible. If I where to recommend, I would go for the second option, option 1 will give you a bunch of If else if else statements which do the same thing while for the third case, regular expressions tend to grow pretty large pretty fast.
Again depending on how much alot is, it could eventually be better to just throw all your strings in a data structure and iterate over it to see if the element is in it.
String[] storage = {
"text",
"foo",
"bar",
"more text"
};
for(int i=0; i < storage.length(); i++){
//Do Something
}
Does this help?

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