-1

I am using the simple code for Sqlite database saving and retrieval. My problem is my code takes always the else part even the strings are same. Toast.makeText(getApplicationContext(), "No UName: "+utext+","+str+"; Pswd: "+ptext+","+str1, Toast.LENGTH_LONG).show();

instead of, Toast.makeText(getApplicationContext(), "Yes UName: "+utext+","+str+"; Pswd: "+ptext+","+str1, Toast.LENGTH_LONG).show();

I checked the output with toast and with debug mode. The value of utext is equal to str and the value of ptext is equal to str1. Is anything I made mistake here? I don't find anything.

http://postimg.org/image/huvmxhgup/

public void onClick(View v) {
            utext=t1.getText().toString();
            ptext=t2.getText().toString();

            Cursor c = db.rawQuery("SELECT * FROM " + tbl_name+" WHERE USERNAME= '"+utext+"' AND PASSWORD= '"+ptext+"'", null);
              if(c.moveToLast() ) {
                      str=c.getString(c.getColumnIndex("USERNAME"));
                      str1=c.getString(c.getColumnIndex("PASSWORD"));
                      Toast.makeText(getApplicationContext(), "True : "+str+", "+str1, Toast.LENGTH_LONG).show();
              }
              else
                  Toast.makeText(getApplicationContext(), "FALSE", Toast.LENGTH_LONG).show();
              if(str==utext || str1==ptext)
                  Toast.makeText(getApplicationContext(), "Yes UName: "+utext+","+str+"; Pswd: "+ptext+","+str1, Toast.LENGTH_LONG).show();
              else
                  Toast.makeText(getApplicationContext(), "No UName: "+utext+","+str+"; Pswd: "+ptext+","+str1, Toast.LENGTH_LONG).show();

        }
Abish R
  • 1,537
  • 3
  • 18
  • 36

2 Answers2

1

In java, == compares the object references and not the content.

== checks whether two strings are the same object,whereas .equals() or .compareTo() checks whether the two strings have the same value.

You can either use the method .equals() or .compareTo() in java to compare strings

Thus, Replace

if(str==utext || str1==ptext)

with

if(str.equals(utext) || str1.equals(ptext))

or

if(str.compareTo(utext)==0 || str1.compareTo(ptext)==0)
Lal
  • 14,726
  • 4
  • 45
  • 70
1

You should always use .equals() for String comparison. Change your code to this.

if(str.equals(utext) || str1.equals(ptext))
    Toast.makeText(getApplicationContext(), "Yes UName: "+utext+","+str+"; Pswd: "+ptext+","+str1, Toast.LENGTH_LONG).show();
else
    Toast.makeText(getApplicationContext(), "No UName: "+utext+","+str+"; Pswd: "+ptext+","+str1, Toast.LENGTH_LONG).show();
Suhas
  • 1,451
  • 14
  • 22