Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android SQLite CursorIndexOutOfBounds

For some reason when the username I input is not found, the application crashes. But when the username is found it seems to run perfect. I even do a check to see if the returned cursor == null. Heres the code

    public boolean isUserAuthenticated(String username, String password) {
    // TODO Auto-generated method stub
    boolean authenticated = false;
    String[] columns = new String[] {LOGIN_USERNAME, LOGIN_PASSWORD};
    String sqlUsername = "\"" + username + "\"";
    Cursor c = ourDatabase.query(LOGIN_TABLE, columns, LOGIN_USERNAME + "="+ sqlUsername, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
        String passwordAttachedToUsername = c.getString(1);
        if(passwordAttachedToUsername.equals(password)) {
            authenticated = true;
        }
    }

    return authenticated;
}
like image 728
user1367263 Avatar asked May 26 '26 16:05

user1367263


1 Answers

Your Cursor object may not be null, but the size of its result set is 0. Instead of:

if (c != null) {
    ...
}

try:

if (c.getCount() > 0) {
    ...
}

Also, as @mu is too short mentioned, you could just use the return value of c.moveToFirst() in your conditional:

if (c.moveToFirst()) {
    String passwordAttachedToUsername = c.getString(1);
    if (passwordAttachedToUsername.equals(password)) {
        authenticated = true;
    }
}
like image 73
Brian Bowman Avatar answered May 30 '26 03:05

Brian Bowman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!