我编写了用于比较数据库中的用户凭据的代码。首先,我检查用户名,然后根据返回的结果,我比较密码。如果两者都匹配,我打开另一个活动。代码对我来说似乎很好,但我没有数据库的经验,我可能会错过这里至关重要的东西。以下代码由于某种原因无效。
public boolean Compare(String username, String pass)
{
Cursor c = sqlDB.query(DB_NAME, columns, DB_COL_EMAIL + "='" + username+ "'", null, null, null, null);
if(c!=null && c.getCount()>0)
{
Toast.makeText(context, "inside check", Toast.LENGTH_SHORT).show();
c.moveToFirst();
int passwordCol_number= c.getColumnIndex(DB_COL_PASS);
boolean found = false;
while(c.moveToNext())
{
found = pass.equals(c.getString(passwordCol_number));
if(found)
return true;
}
}
return false;
}
我做错了什么吗?
此致
答案 0 :(得分:1)
您应该将方法增强为
public boolean compareLogin(String username, String pass) {
String where = DB_COL_EMAIL + " = ? AND " + DB_COL_PASS + " = ?";
String[] whereParams = new String[]{username, pass};
Cursor mCursor = db.query(DB_NAME, columns,
where,
whereParams,
null,
null,
null);
if (mCursor != null && mCursor.moveToFirst())
return true;
else
return false;
}
是的,你应该读一下java或Android中的命名约定。
答案 1 :(得分:0)
我唯一看到的是你没有关闭光标。
做同样的事情:
Cursor c = null;
try {
/* your stuff in here */
} finally {
if (c != null) c.close();
}
答案 2 :(得分:0)
这应该按照你想要的方式工作。
public boolean Compare(String username, String pass) {
Cursor c = sqlDB.query(DB_NAME, columns, DB_COL_EMAIL + "='" + username+ "'", null, null, null, null);
// No need to check c != null and c.getCount()
// c will not be null even if no rows returned.
boolean found = false;
// c.moveToFirst() will return false if no rows returned
// so this line should be sufficient
if (c.moveToFirst()) {
// while (c.moveToNext()) should be commented
// remember you just called moveToFirst()?
// moveToNext() will move to next row
// and will returned false if no more rows in the cursor
found = pass.equals(c.getString(passwordCol_number));
}
c.close();
return found;
}