Reputation: 1
I'm currently doing my final year project on android app. I tried to make a login module, but it always gives me an error for that part:
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
"size of 1" is the user data that I try to get; however, I can't figure out where to go from here. Can anyone help me solve this issue? Here's my code:
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;
}
Upvotes: 0
Views: 428
Reputation: 101
You should move the Cursor to the first row before fetching data
Cursor d = agentDatabase.rawQuery("SELECT * FROM " + DATABASE_TABLE + " WHERE " + KEY_USERNAME + " = ?", new String[]{user});
d.moveToFirst();
This will work if you only expect one row in the result cursor, otherwise you can use d.move
.
Upvotes: 1