I am trying to find if the username exists in the database, if it exists then a boolean variable will be set to true if not it will be set to false. It seems like the variable always set to true even when the username does not exist in the table. I have checked the data in the table and tried many times but the variable is always set to true and the message “Username exists” is always shown no matter if the username is in the database or not. This is my code. What am I doing wrong?
—-Login Class that that defines the buttons and edit text fields and fires message when login button is clicked————-
public class Login extends Activity{
Button sqllogin;
EditText sqlusername, sqlpassword;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
sqlusername = (EditText) findViewById(R.id.etuname1);
sqlpassword = (EditText) findViewById(R.id.etpass);
sqllogin = (Button) findViewById(R.id.bLogin);
sqllogin.setOnClickListener(new View.OnClickListener() {
//Method that fires a message when the Login button is clicked
public void onClick(View v) {
switch (v.getId()){
case R.id.bLogin:
String username = sqlusername.getText().toString();
String password = sqlpassword.getText().toString();
DBAdapter entry = new DBAdapter(Login.this);
entry.open();
boolean r = entry.findUsername(username);
if(r == true){
Toast.makeText(Login.this, "Username Exists", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(Login.this, "Username does not Exists", Toast.LENGTH_LONG).show();
}
entry.close();
break;
}
}
});
}
}
———Method in DBAdpater class that check if username exists in the table————
public boolean findUsername(String username) {
Cursor c = ourDatabase.query(true, DATABASE_TABLE_L, new String[] {
KEY_USERNAME, KEY_PASSWORD}, KEY_USERNAME + "='"
+ username +"'", null, null, null, null, null);
if (c!= null) {
return false;
}
else{
return false;
}
}
Instead of checking to see if cursor is null try checking if cursor contains any data, for example:
getCount() returns the number of rows returned by the query.