I am trying to make a simple login System. And This is the coed in database class. Is my Method correct? It should return true if both username and password are correct and false if either one of them is wrong or not in the database(not registered)? Is there any simpler way to code this method?
public boolean getAccount(String name, String password) {
int test = 0;
database = getReadableDatabase();
String sql = "SELECT * FROM tbl_account WHERE username='name' AND password='password'";
Cursor c = database.rawQuery(sql, null);
if (c.moveToFirst()) {
do {
if (c.getString(0).isEmpty()) {
test = 0;
}
else if (c.getString(0).isEmpty() == false) {
if (name.equals(c.getString(0))) {
if (c.getString(1).isEmpty()) {
test = 0;
}
else if (password.equals(c.getString(1))) {
test = 1;
}
}
}
} while (c.moveToNext());
}
if (test == 0) {
return false;
} else {
return true;
}
}
2 Answers 2
Best practice is to use ? placeholders with selection arguments where you can:
String sql = "SELECT * FROM tbl_account WHERE username = ? AND password = ?";
Cursor c = database.rawQuery(sql, new String[] {name, password});
This avoids problems where the arguments themselves contain characters such as quotes and apostophes that could otherwise break your constructed SQL string.
1 Comment
I think your sql should be:
String sql = "SELECT * FROM tbl_account WHERE username='" + name +
"' AND password='" + password + "'";
try this sql. hope it will help.