Can't check string value - java

I am trying to check a string value in if but it always is entering the else,
what Is wrong here? Thank you
public void alertBtn(View v){
EditText text = (EditText)findViewById(R.id.editText1);
String value = text.getText().toString();
String password="asd";
if (value==password){
new AlertDialog.Builder(this)
.setTitle("Success")
.setMessage("Correct Password")
.setNeutralButton("OK", null)
.show();
}
else
new AlertDialog.Builder(this)
.setTitle("Error")
.setMessage("Wrong password")
.setNeutralButton("OK", null)
.show();
}

Using the == operator will compare the references to the strings not the string themselves.
String value = text.getText().toString();
String password="asd";
if (value.equals(password))
{
}

use equals() function
Try
if( value.equals(password) ) {
}

Use .equals or .equalsIgnoreCase() to compare strings
What is the difference between == vs equals() in Java?
if (value.equals(password)){
Also move the initialization of editText to onCreate. There is no need to initialize edittext everytime on button click
text = (EditText)findViewById(R.id.editText1); // in onCreate
and declare EditText text as class member

Look here
Use the String.equals(String other) function to compare strings, not the == operator.
The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with ==, but it's better not to rely on that.

Related

How to verify if a string contains a whole other string?

So I have this method which returns true if the validation is correct:
private boolean validation() {
String emailStr = etEmail.getText().toString();
if (emailStr.trim().isEmpty()) {
etEmail.setError(getResources().getString(R.string.eroareEmpty));
return false;
} else if (!emailStr.endsWith("stud.ase.ro") && emailStr.length() <= 15) {
etEmail.setError(getResources().getString(R.string.eroareEmail));
return false;
}
return true;
}
I want to verify that the text i type in EditText etEmail contains (only at the end of the string) "stud.ase.ro", the whole string not just a part of it.
In simple words, i want to verify if the email ends with "stud.ase.ro" and nothing else.
Currently my method returns true, even if i type something unsual like "hellllllllllllooo#stud", which it shouldn't do.
To match at the end of the string, use the String.endsWith method.
if (str.endWiths("hello123#stud")) {
//bla bla
}
You might want to improve your code. You're using EditText right?
EditText.getText() does not return null
You should create a local variable for repeated code access the text inside EditText: String emailStr = etEmail.getText().toString()
It will increase readability a lot.

If else structure not setting correct url in android app?

The if else structure is not setting correct url even though location and category parameters
are correctly parsed i have checked it using log messages.
private void initView(String location,String category) {
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url;
if(location.toString()=="Jaipur" && category.toString()=="Gardner")
url = "http://192.168.186.1/apps_jaipur_gardner.php";
else if(location.toString()=="Jaipur" && category.toString()=="Mason")
url = "http://192.168.186.1/apps_jaipur_mason.php";
else if(location.toString()=="Jaipur" && category.toString()=="Carpenter")
url = "http://192.168.186.1/apps_jaipur_carpenter.php";
else if(location.toString()=="Jaipur" && category.toString()=="Plumber")
url = "http://192.168.186.1/apps_jaipur_plumber.php";
else
url = "http://hello.hostei.com/appsonline.php";
Log.d(TAG,location);
Log.d(TAG,category);
Log.d(TAG,url);
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
You are making a very big mistake! Strings are reference types, when you use == to compare two reference types, you are comparing the location in memory of those two strings but not whether they have the same characters. This is a mistake that many beginners will make so don't worry, you are not alone.
Instead, you should use the equals method in the String class. That method compares what we all want - the characters!
You should do something like:
if (location.equals("Jaipur") && category.equals("Gardener"))
try .equals instead of ==
May be this can help you

compare two strings with .equals() don't work

I get a string form a list and try to compare it with some strings in the values and then do some stuff
for(int i=0; i<sizeOfList; i++){
String LIST_TITLE;
LIST_TITLE = list_title.get(i); //the List list_title includes some strings
if(LIST_TITLE.equals(R.string.percentbattery)) {
//do stuff
Log.d("EQUAL!","" + LIST_TITLE);
} else if(LIST_TITLE.equals(R.string.screenrecorder) == true) {
//do stuff
Log.d("EQUAL!","" + LIST_TITLE);
} else if(LIST_TITLE.equals(R.string.eightsms) == true) {
//do stuff
Log.d("EQUAL!","" + LIST_TITLE);
} else {
// do stuff
Log.e("TITLE NOT EQUAL","" + LIST_TITLE);
}
}
If I compare my LIST_TITLE with the (R.string. ...) in my Logcat they are equal, but I get only the "TITLE NOT EQUAL" Log from the else statement.
Is there another way to compare these strings? the "==" method also don't work.
R.string.percentbattery is not a String, it's an Integer that is the ID to reference the string.
what u want is:
LIST_TITLE.equals(context.getResources.getString(R.string.percentbattery))
LIST_TITLE.equals(R.string.percentbattery)
This is incorrect, because you're trying to compare string with resource ID
You should get the string from resource first:
LIST_TITLE.equals(getResources().getString(R.string.percentbattery))
R.string.xxx is an int. You need to get the String from that res
Something like
if(LIST_TITLE.equals(getResources().getString(R.string.percentbattery)))
This is assuming you have Activity Context available. Otherwise, you would need to add a Context variable in front of getResources()
R.string.some_id is just an integer by which you can get the String from the resources.
So in order to compare Strings correctly in you case you have to do:
String precentBattery = getResources().getString(R.string.percentbattery);
if (LIST_TITLE.equals (percentBattery)) ...

Comparison between textPersonName and textPassword [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
My activity it's a simple login activity where (for tests only) it will return true if the username && password are equal and false if not.
But it always return false.
Not even if I convert toString(); example:
String a=(txtUserName.getText().toString() == txtPassword.getText().toString()) ? "equal" : "Nequal";
Full code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
txtUserName = (EditText) this.findViewById(R.id.txtUname);
txtPassword = (EditText) this.findViewById(R.id.txtPwd);
btnLogin = (Button) this.findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(LoginActivity.this,txtUserName.getText(),Toast.LENGTH_LONG).show();
Toast.makeText(LoginActivity.this,"Just for separate", Toast.LENGTH_LONG).show();
Toast.makeText(LoginActivity.this,txtPassword.getText(), Toast.LENGTH_LONG).show();
String a=(txtUserName.getText() == txtPassword.getText()) ? "equal" : "Nequal";
Toast.makeText(LoginActivity.this, a, Toast.LENGTH_LONG).show();
}
});
}
Use
String a=(txtUserName.getText().toString().equals(txtPassword.getText().toString()))
The way you are doing are not equating string rather they are equating string objects.
Always use String.equals() method for string comparison.
Java String.equals versus ==
To compare string values, use String's equals method; the == operator for object references compares for reference equality and since they are two different objects it will always return false.
txtUserName.getText().equals(txtPassword.getText())

trying to detect a string from a pair in a set

For some reason, my == operator isn't returning true when it should. I see two of the exact same strings displayed on my phone yet it's still not registering as true. Any ideas? It's a hashset of pair (string,int). getFirst returns the string in the pair.
private boolean contains(HashSet<Pair> mySet, String current) {
Iterator<Pair> temp = mySet.iterator();
String compared;
Toast.makeText(MainActivity.this, " want " +current,
Toast.LENGTH_LONG).show();
while (temp.hasNext()) {
compared = temp.next().getFirst();
Toast.makeText(MainActivity.this, compared+" "+current,
Toast.LENGTH_SHORT).show();
if (compared==current)
Toast.makeText(MainActivity.this, "found", Toast.LENGTH_SHORT).show();
}
return false;
}
Strings should not be compared with ==. In java, Strings are objects, and == will check if they are the same object reference. If you want to check if they contain the same sequence of characters, use string.equals(otherString).
Do this instead:
if(compared.equals(current))
Use the String.equals() method for comparing strings. As in if (string1.equals(string2))....

Categories