我目前正在Android应用程序上完成我的最后一年项目。我试图创建一个登录模块,但它总是给我一个错误:
android.database.CursorIndexOutOfBoundsException:请求索引-1,大小为1
“size of 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;
}
答案 0 :(得分:0)
您应该在获取数据之前将光标移动到第一行
Cursor d = agentDatabase.rawQuery("SELECT * FROM " + DATABASE_TABLE + " WHERE " + KEY_USERNAME + " = ?", new String[]{user});
d.moveToFirst();
如果您只希望结果光标中有一行,这将有效,否则您可以使用d.move
。