Simple if statement stops code from working [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I'm having a problem with a simple if statement and i'm not too sure why. I've got an edittext box and a button, when the user inputs a value into the edittext and then presses the button, whatever was input into the box is converted to string and stored in a variable, this variable is then displayed in a toast. Now this works perfectly fine as it is but I would like it to only display if a certain value is input into the editbox but when I put in an if statement to validate this, it seems to completely disgregard the if statement and does nothing. It does not cause any errors but it stops any toast from being displayed even if the correct string is input. I'm sure this is something simple but I can't seem to work it out. It would be great if anyone could work out why it does this.
Code below:
Working code when the if statement is commented out:
saveBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Global.controlNum = inputTxt1.getText().toString();
// if((Global.controlNum == "1")||(Global.controlNum == "2" )){
Toast toast= Toast.makeText(SettingsScreen.this,"hello " + Global.controlNum, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, -100);
toast.show();
// }
}
});
if the if statement is brought in then it will do nothing:
saveBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Global.controlNum = inputTxt1.getText().toString();
if((Global.controlNum == "1")||(Global.controlNum == "2" )){
Toast toast= Toast.makeText(SettingsScreen.this,"hello " + Global.controlNum, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, -100);
toast.show();
}
}
});

Read about How do I compare strings in Java?
So Simply change
if((Global.controlNum == "1")||(Global.controlNum == "2" ))
With
if(("1".equals(Global.controlNum))||("2".equals(Global.controlNum) ))

you should change it with:
if((Global.controlNum == "1")||(Global.controlNum == "2" ))
to
if((Global.controlNum.equals("1"))||(Global.controlNum.equals("2") ))

You should use equlas() to compare String
Global.controlNum.equlas("1")

Try replacing
if((Global.controlNum == "1")||(Global.controlNum == "2" ))
with
if((Global.controlNum.equalsIgnoreCase("1"))||(Global.controlNum.equalsIgnoreCase("2") ))

Use Global.controlNum.equals("1")
If you want to compare Strings in Java (Android) always use the method equals(String) or equalsIgnoreCase(String)

Related

if statement always returning false on string comparison [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
I have used this code to try and confirm that the user input
passwords are the same and there is no mismatch, before proceeding to
the next activity. But the if statement always returns a false. It works fine for hardcoded text, but always returns a false for if. Am I missing something?
private void validate(EditText userPassword, EditText userConfirmPassword){
String userPasswordtext = userPassword.getEditableText().toString();
String userConfirmPasswordtext = userConfirmPassword.getEditableText().toString();
if(userPasswordtext == userConfirmPasswordtext){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}else{
Toast a=Toast.makeText(this, "Passwords do not match", Toast.LENGTH_SHORT);
a.show();
}
}
Use .equals when comparing two strings
if (userPasswordtext.equals(userConfirmPasswordtext)) {

If statement constantly activating in android

I am working on some code that will allow the program to check if the user has entered a name and a birth day and decide if the birthday is today and play happy birthday. However while I have managed to get the program to use the correct date and play the songs the if statements do not seem to be working properly. When ever I enter the current date as the birthday the happy birthday song always starts up even when the name box is empty and it should ask for your name. This only happens when the birthday textbox and the current day match, so could anyone help me to get my if statement working correctly. Here is my if statement code.
if((btn==v) && (name.getText().toString()!="") && (bday.getText().toString()!="") && (bday.getText().toString().equals(formatdate))){
String msg1 = "Today is " + sdf.format(cdate.getTime()) + ". Happy Birthday, " + name.getText() + "!";
toast = Toast.makeText(this, msg1, Toast.LENGTH_SHORT);
toast.show();
//Context context = null;
mp.start();
//mp.stop();
response.setText(msg1);
}else if(btn==v && name.getText().toString().equals("") && bday.getText().toString()!=""){
String msg3 = "Please enter your name.";
toast = Toast.makeText(this, msg3, Toast.LENGTH_SHORT);
toast.show();
mp.stop();
response.setText(msg3);
}else if(btn==v && name.getText().toString()!="" && bday.getText().toString().equals("")){
String msg4 = "Please enter your birthday.";
toast = Toast.makeText(this, msg4, Toast.LENGTH_SHORT);
toast.show();
response.setText(msg4);
}else if(btn==v && name.getText().toString().equals("") && bday.getText().toString().equals("")){
String msg5 = "Please enter your name and birthday.";
toast = Toast.makeText(this, msg5, Toast.LENGTH_SHORT);
toast.show();
response.setText(msg5);
}else{
String msg2 = "Today is " + formatdate + ". Sorry today is not your birthday.";
toast = Toast.makeText(this, msg2, Toast.LENGTH_SHORT);
toast.show();
response.setText(msg2);
}
There are a few things that you need to change. You don't need to do this:
name.getText().toString()
You can get rid of the toString() part.
Second. Instead of doing something like this:
name.getText().toString()!=""
Change it to this:
!name.getText().equals("")
Because .equals() returns a boolean and you can't compare strings with == or != etc.
Finally, you need to make sure not to use b == v but b.equals(v)
I think the problem lies in the "!=" operator. In Java, the operator "==" and "!=" only compare if the referenced object is equal. It means the object only "==" itself. While the ".equals()" function compares the content of two objects. You should always use "equals()" function to compare the content of two objects.
use
btn.euqals(v);
!name.getText().toString().equals("");
instead.
In Java the == operator is a simple comparison of values. For
object references, the values are the references, so x == y
returns true if x and y reference the same object.
no need of toString() for getText() since it itself returns string.
change bday.getText().toString()!="" to !bday.getText().equals("")
change name.getText().toString()!="" to !name.getText().equals("")

Why won't my JOptionPane show up if there's no text in my JTextField? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm working on a login screen for my game, and everything works fine, except for one thing. When I check to see if the text from the JTextField == "", it still launches the game and whatnot.
Here's a look at my code:
public void attemptLogin(String username, String passcode) {
if (username != "" && passcode != "") {
System.out.println(username);
System.out.println(passcode);
} else if (username == " " || passcode == " ") {
JOptionPane.showMessageDialog(null, "Put in your credentials!", "Hey you!", JOptionPane.ERROR_MESSAGE);
}
}
}
In my main class, it goes:
public void actionPerformed(ActionEvent action) {
if (action.getSource() == login) {
gamelogin.attemptLogin(username.getText(), passcode.getText());
} else if (action.getSource() == register) {
account.registerAccount();
}
}
Now what must happen is that if the JTextField comes up blank, then show a JOptionPane and if not, login to the game (added later), but evidently, this is not happening. It just outputs white space in the console.
Thanks in advance! :)
You need to use the equals-method for comparing strings. Neither of your comparisons will ever be true at the moment.
username.equals("") && passcode.equals("")

if statement erroron button click

can someone please help making pairs game and using this if statement can someone tell me if theres a bracket or semi colon missing cant see whats missing (pic2.getTag() == beck) is underlined have 4 buttons want to pair or reset them the buttons start with set tag name (boots) this works but no good for non match
This works
if (pic2.getTag() == pic1.getTag()){
pic1.setVisibility(View.INVISIBLE);
pic2.setVisibility(View.INVISIBLE);}
THis doesnt
pic1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
pic1.setTag(beck);
pic1.setBackgroundResource(R.drawable.becks);
if (pic2.getTag() == beck) {
pic1.setVisibility(View.INVISIBLE);
pic2.setVisibility(View.INVISIBLE);
}
}
});
The problem is in the compare operator ==. View tags are Objects (most probably Strings), so you need to compare them with equals.-
if (pic2.getTag().equals(pic1.getTag()))
and
if (pic2.getTag().equals(beck))

How to get Spinner Selected Item in Android

I am making a currency converter with two spinners. I want to make an "if" function using the values of the spinner's selected item like below.
#Override
public void onClick(View v) {
if (spinner1.getSelectedItem()=="Dollars" && spinner2.getSelectedItem()=="Euros") {
convertDollarstoEuros();
}
if (spinner1.getSelectedItem()=="Euros" && spinner2.getSelectedItem()=="Euros") {
convertEurostoEuros();
}
Toast.makeText(MainActivity.this,
"OnClickListener : " +
"\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) +
"\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()),
Toast.LENGTH_SHORT).show();
}
The problem is that the toast is showing, but the currencies aren't converting. The toast part is working, but the spinner part isn't. Any help would be greatly appreciated. Here is my LogCat:
Try this :
if (spinner1.getSelectedItem().toString().equals("Dollars") && spinner2.getSelectedItem().toString().equals("Euros")
...
getSelectedItem() returns an Object . info . So you have to get the corresponding string first.
Then java compares strings using equals().
if (spinner1.getSelectedItem()=="Dollars" && spinner2.getSelectedItem()=="Euros") {
You can't compare Strings like that. You have to use the equals() method to compare them. Use this:
if (spinner1.getSelectedItem().toString().equals("Dollars") && spinner2.getSelectedItem().toString().equals("Euros")) {}
Check whether you called the id correctly or not? When I was working when improper id was called this exception used to arise. For eg In TextView, findViewById(R.id.textView1) but in xml file we may have set it to textView2.

Categories

Resources