Android SQLite CursorIndexOutOfBounds

For some reason, when the input username is not found, the application crashes. But when the username is found, it seems flawless. I even check to see if the returned cursor returned == null. Here is 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;
}
+3
source share
5 answers

A Cursor object cannot be null, but the size of its result set is 0. Instead:

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

to try:

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

Also, since @mu is too briefly said, you can simply use the return value of c.moveToFirst () in your conditional expression:

if (c.moveToFirst()) {
    String passwordAttachedToUsername = c.getString(1);
    if (passwordAttachedToUsername.equals(password)) {
        authenticated = true;
    }
}
+3
source

Firstly, the condition should be:

if (c != null && c.getCount() > 0)

Secondly, you can reorganize

String passwordAttachedToUsername = c.getString(1);
if(passwordAttachedToUsername.equals(password)) {
    authenticated = true;
    }

instead of this:

authenticated = password.equals(c.getString(1));
+2
source

:

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

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

true, c != null 0.

+1

The command querywill always return the cursor so that your null test always fails. You need to check the counter containing the cursor withcursor.getCount()

0
source
if (cursor != null && cursor.getCount() > 0) {
if (c.moveToFirst()) {
          String passwordAttachedToUsername = c.getString(1);
          if(passwordAttachedToUsername.equals(password)) {
           authenticated = true;
    }}
                    // your logic goes here
                } else {
                    Toast.makeText(getApplicationContext(), "No Record Found", 1000).show();
                }
0
source

All Articles