0

我目前正在做我的最后一年的安卓应用项目。我试图制作一个登录模块,但它总是给我该部分的错误:

android.database.CursorIndexOutOfBoundsException:请求索引-1,大小为1

“大小为 1”是我尝试获取的用户数据;但是,我不知道从这里去哪里。谁能帮我解决这个问题?这是我的代码:

    Cursor c = agentDatabase.rawQuery("SELECT COUNT(username) FROM " + DATABASE_TABLE + " WHERE " + KEY_USERNAME + " = ? AND " +KEY_PASSWORD + " = ?", new String[]{user, pass});

    String result = "";

    if(c != null && c.moveToPosition(0)){
        //if (c.moveToFirst()){

            int r = c.getCount();

            if(r == 1){
                //Cursor d = agentDatabase.rawQuery("SELECT * FROM " + DATABASE_TABLE + " WHERE " + KEY_USERNAME + " = '" + user + "'", new String[]{ KEY_ROWID, KEY_NAME, KEY_EMAIL, KEY_USERNAME});

                Cursor d = agentDatabase.rawQuery("SELECT * FROM " + DATABASE_TABLE + " WHERE " + KEY_USERNAME + " = ?", new String[]{user});

                int iRow = d.getColumnIndex(KEY_ROWID);
                int iName = d.getColumnIndex(KEY_NAME);
                int iEmail = d.getColumnIndex(KEY_EMAIL);
                int iUser = d.getColumnIndex(KEY_USERNAME);

                result = result + d.getString(iRow) + " " + d.getString(iUser) + " " + d.getString(iName) + " " + d.getString(iEmail) + "\n";

            }
        //}
    }

    return result;
}
4

1 回答 1

1

您应该在获取数据之前将光标移动到第一行

Cursor d = agentDatabase.rawQuery("SELECT * FROM " + DATABASE_TABLE + " WHERE " + KEY_USERNAME + " = ?", new String[]{user});
d.moveToFirst();

如果您只希望结果游标中有一行,这将起作用,否则您可以使用d.move.

于 2012-05-02T13:30:57.597 回答