0

我想在 Android 中使用只有用户名的登录系统。下面的代码仅适用于第一行(例如,我的数据库有名称:1- Joseph 2 - Najib,如果我输入 Joseph 它工作正常,但如果我输入 Najib 或我的数据库中不存在的其他值程序显然一直在循环并且没有响应..如何更正此代码以相应地返回消息(数据库中的用户名或无效的用户名)?我在 while 语句中有错误吗?

public void checklogin() {

    DatabaseHelper dbh = new DatabaseHelper(LoginActivity.this);
    DatabaseAdapter dba = new DatabaseAdapter(LoginActivity.this);
    db = dbh.getWritableDatabase();
    TextView usernametry = (TextView) findViewById(R.id.usernametry);
    String usertry = usernametry.getText().toString();

    String[] allColumnsofuserstable = { dba.COLUMN_ID, dba.COLUMN_NAME,
            dba.COLUMN_AGE, dba.COLUMN_GENDER, dba.COLUMN_WEIGHT,
            dba.COLUMN_HEIGHT, dba.COLUMN_CALORIES };

    Log.d("TAG", usertry);

    Cursor mCursor = db.query(dba.TABLE_USERS,
            new String[] { dba.COLUMN_NAME }, null, null, null, null, null,

    mCursor.moveToNext();
    while (!mCursor.isAfterLast()) {
        String k = mCursor.getString(0);
        if (k.equalsIgnoreCase(usertry)) {
            Toast.makeText(LoginActivity.this,
                    "Logged in as " + mCursor.getString(0).toString(),
                    Toast.LENGTH_LONG).show();
            mCursor.moveToNext();
        } else
            Toast.makeText(LoginActivity.this, "invalid username",
                    Toast.LENGTH_LONG).show();
    }

    mCursor.close();
    dbh.close();
    return;
}
4

2 回答 2

1

最好的办法是修改您的查询以查找字符串,而不是获取所有结果并循环进行查找。

Cursor mCursor = db.query(dba.TABLE_USERS,
new String[] { dba.COLUMN_NAME }, dba.COLUMN_NAME + "=?", new String[]{usertry},
null, null, null);
于 2012-04-23T21:17:04.690 回答
0

mCursor.moveToNext();您的循环已中断,因为您仅在在数据库中找到用户名的情况下移动光标 ( ) 中的指针。光标在最后一项之后不能移动并且while (!mCursor.isAfterLast())永远不会停止。

您需要确保始终移动光标。比如像这样:

Cursor mCursor = db.query(dba.TABLE_USERS,
        new String[] { dba.COLUMN_NAME }, null, null, null, null, null,

boolean loggedIn = false;
while (mCursor.moveToNext()) {
    String k = mCursor.getString(0);
    if (k.equalsIgnoreCase(usertry)) {
        Toast.makeText(LoginActivity.this,
                "Logged in as " + mCursor.getString(0).toString(),
                Toast.LENGTH_LONG).show();
        loggedIn = true;
        break;
    }
}
if (!loggedIn)
        Toast.makeText(LoginActivity.this, "invalid username",
                Toast.LENGTH_LONG).show();

或者您更改查询(请参阅@Waqas)为您完成工作(LIKE ?= equalsIgnoreCase= ?= equals

Cursor mCursor = db.query(dba.TABLE_USERS,
    new String[] { dba.COLUMN_NAME }, dba.COLUMN_NAME + " LIKE ?", new String[]{usertry},
    null, null, null);

if (mCursor.moveToFirst()) {
    String k = mCursor.getString(0);
    Toast.makeText(LoginActivity.this,
            "Logged in as " + mCursor.getString(0).toString(),
            Toast.LENGTH_LONG).show();
} else {
        Toast.makeText(LoginActivity.this, "invalid username",
                Toast.LENGTH_LONG).show();
}
于 2012-04-23T21:51:27.457 回答