trouble comparing two string variables with different refrences - android

I am trying to check user's inserted password with saved password in the database.
This is my methode:
private Boolean CheckPassword()
{
TextView txt_pass = (TextView) findViewById(R.id.login_password_txt);
String _writtenPassword = txt_pass.getText().toString().trim();
if (_writtenPassword == userPassword)
return true;
Log.d(TAG, userPassword);
Log.d(TAG, _writtenPassword);
Log.d(TAG, String.valueOf(userPassword.length()));
Log.d(TAG, String.valueOf(_writtenPassword.length()));
return false;
}
The log shows me the password and length.
The result is:
123
123
3
3
But this methode returns False!!!
Can anyone help me please?

Try this..
String you should compares with .equals("")
if (_writtenPassword.equals(userPassword))
return true;
== always just compares two references
Refer this String comparison

Use the if-else control structure and also use the equals() for comparing two strings like this,
if (_writtenPassword.equals(userPassword))
return true;
else
return false;

Alternatively you can use matches
if (_writtenPassword.matches(userPassword))
return true;
///your code

expression _writtenPassword == userPassword is true whenever reference of _writtenPassword and userPassword are same.
Since you don't care about their reference but you care about their value so use expression
_writtenPassword.equals(userPassword)which is true whenever the value of_writtenPasswordanduserPassword` are same.
Try this:
return _writtenPassword.equals(userPassword);

Related

Can anyone suggest me that below if condition is wrong or not? [duplicate]

This question already has answers here:
Check whether a String is not Null and not Empty
(35 answers)
Closed 6 years ago.
May occur any exception in coding for checking string is null or not ? Please help.
String code ;
if (!code.equals(null)) {
}
else
{
}
Here is how you can check if String value is null or not
if(code != null){
}else{
}
You can not us !code.equals(null) because, equals is used to compare same object type. null is not any object type and code is String. If you consider null as String, then you can use !code.equals("null")
String can be checked like this:
if(code.equals("null") || code.equals("")) {
// code to do when string is null.
}
else {
// code to do when string is not null.
}
equals() is use to check the similarity of two String, and == or != is use to check the condition. In your case you are checking the similarity of string.
if (!code.equals(null)) {
//code checks that String code is equal to null or not
}
else
{
}
another
if (code != null) {
//code checks if code is not equals to null (condition checking)
}
else
{
}
There are many ways to check if String is empty in Java, but what is the right way of doing it? right in the sense of robustness, performance and readability. If robustness is your priority then using equals() method or Apache commons StringUtils is the right way to do this check. If you don't want to use third party library and happy of doing null check by yourself, then checking String's length is the fastest way and using isEmpty() method from String is most readable way. By the way, don't confuse between empty and null String, if your application treat them same, then you can consider them same otherwise they are different, as null may not be classified as empty. Here are three examples of checking String is empty or not by using JDK library itself.
Read more Here
You can't use .equals(null) to make a null check, because the API description for Object#equals states that:
For any non-null reference value x, x.equals(null) should return false.
Not only would this be a useless check (since it always returns false), it would also throw a NullPointerException if code actually was null, because a null value does not define an equals method.
Object x = null;
boolean isNull = x.equals(null); // NullPointerException on .equals
The only practical way to do a null check is to use:
if (code != null) {
}
If you want to check whether string is empty i.e. null or "" then use
if(TextUtils.isEmpty(code)){
}else{
}
equals checks the value exists in string.

How do I check a boolean string array list for a valid response in android?

I'm writing a text based game where movement is dictated by typing "go left," "go right," etc. I have a Boolean Array List with the valid commands, and I want to compare what the user types to the members in the array. The code I have rejects all commands as invalid. I believe it's because I'm returning false, but I'm not sure how to fix it. I'm very new to this, so any and all help is appreciated.
private boolean validCommand() {
ArrayList<Boolean> validCommand = new ArrayList<>();
validCommand.add(Boolean.valueOf("go left"));
validCommand.add(Boolean.valueOf("go right"));
validCommand.add(Boolean.valueOf("go straight"));
validCommand.add(Boolean.valueOf("go back"));
for (boolean checkCommand : validCommand) {
if (typeCommand.getText().toString().equals(checkCommand))
return true;
}
return false;
}
typeCommand is just the EditText the user types their command in.
you don't have to use ArrayList<Boolean>. you have to use ArrayList<String>.
Because you want to compare String to String.
private boolean validCommand() {
List<String> validCommand = new ArrayList<>();
validCommand.add("go left");
validCommand.add("go right");
validCommand.add("go straight");
validCommand.add("go back");
// List#contains() will return true if List contains arg, or false not.
return validCommand.contains(typeCommand.getText().toString());
}
Boolean.valueOf(String s) returns the boolean value of the string, ie "true" would return true. If you have random string, like "go left", it will return false. So if validity is your concern, I would change the array to an array of strings instead and compare the array string with what was typed. If the comparison returns true then you have a valid command.

Android comparing strings with == to each objects

I'm coming from C#, so typically I try to relate everything that i'm doing.
I cannot figure out why the below statement doesn't work. Basically String val = "admin". Then an I have an if statement, however the if statement is always false. I'm sure it's something simple.
Thanks!
EditText edt = (EditText) findViewById(R.id.email);
//String val = edt.getText().toString();
String val = "admin";
EditText edt2 = (EditText) findViewById(R.id.password);
String val2 = edt2.getText().toString();
if(val.toString() == "admin") {
String hero = val;
}
You should use
if (val.equals("admin")) {
String hero = val;
}
instead of using an equal sign. Using an equal sign in java is asking if they're the same object, which will be false even if the strings are the same.
Also, be careful with what you're doing inside of the if statement, because the variable "hero" won't be accessible outside of that block.
In Java you can't compare strings using ==
You need to change your if statment like this
if(val.equals("admin")){}
First of all you have never changed the value of String val to anything so there is no need to try convert it to a string in your if statement.
String val = "admin";
if (val == "admin") {
//code here
}else{
//code here
}
Hope this helps
In java, == operator check the address of each value, and equals() method check the value.
So If you want to compare the value of each string, you should use the equals() method.
Please search for the concept of 'call by reference' and 'call by value'.
And you already declare val to String, so it didn't need toString().
if(val.equals("admin")) {
String hero = val;
}
I'm surprised no one mentioned the difference between .matches() and .equals() depending on your needs, what you could also be looking for is .matches()
if(val.toString().matches("admin")) {
String hero = val;
}
Matches checks the match of a String to a regular expression pattern, not the same string.
For example:
"hello".equals(".*e.*"); // false
"hello".matches(".*e.*"); // true
use .equals() instead of ==.
for example:
if (val.equals("admin")) ...

Android - If doesn't work i am getting string from text box

if condition doesn't validate the value inside string mentioned below.
//getting input box value
newText = input.getText().toString();
//using if condition newText got value "a"
if (newText=="a")
{
//do something
}
but the above if condition doesn't work i check string got right value which is a.
thanks in advance
In java you should use equals method to compare the values of strings:
if ("a".equals(newText)) {
//do something
}
To compare the references you can use ==. For more information check this: https://stackoverflow.com/a/513839/3225458

"==" for Strings always returning false [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I can't seem to get the code within the second if statement to execute. I have logged both values being compared and also ran the debugger and checked them. They are both "a". It always shows the incorrectPasswordDialog. This question seems difficult because it seems as though it should just work but any help is appreciated.
private void logUserIn(AppUser user) {
if (user != null){
Log.d("mPassword: ", mPassword);
Log.d("user.getPassword(): ", user.getPassword());
String userPassword = user.getPassword().toString();
String formPassword = mPassword.toString();
if ( userPassword == formPassword ){
Intent welcomePage = new Intent(this, StartScreenActivity.class);
welcomePage.putExtra("name", mName);
startActivity(welcomePage);
}
else {
showIncorrectPasswordDialog();
}
}else {
showIncorrectUserNameDialog();
}
}
You are comparing the object identity. Use string.equals() to check for equivalence.
if(userPassword.equals(formPassword)){
}
Change
if ( userPassword == formPassword ){
to
if ( userPassword.equals(formPassword) ){
== compares object references, whereas .equals compared String values.
You can not compare string using ==
try like this
Compares the specified object to this string and returns true if they are equal. The object must be an instance of string with the same characters in the same order.
if ( userPassword.equals(formPassword)){
// do some stuff
}
or
Compares the specified string to this string ignoring the case of the characters and returns true if they are equal.
if(userPassword.equalsIgnoreCase(formPassword))
{
//do some stuff
}
In JAVA to compare between strings, you should use:
if(userPassword.equals(formPassword)) {
// they are equal
}
Change
if ( userPassword == formPassword ){
to
if ( userPassword.equals(formPassword)){
In Java, String comparison is done with .equals(). Using == compares the object reference and not their values.
Java String comparison
In JAVA you should use equals to judge equal of value of different String.
== is used to judge object pointer for string, so it would only return false in your case.

Categories

Resources