user1367263
user1367263

Reputation: 53

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;
}

Upvotes: 3

Views: 792

Answers (5)

Nitin
Nitin

Reputation: 258

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();
                }

Upvotes: 0

Alex Lockwood
Alex Lockwood

Reputation: 83303

Change:

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

to

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

which will return true if c != null and the size of the cursor is greater than 0.

Upvotes: 1

anon
anon

Reputation: 4192

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;
    }
}

Upvotes: 3

Federico Cristina
Federico Cristina

Reputation: 2223

First, the condition should be:

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

Second, you can refactor

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

with this instead:

authenticated = password.equals(c.getString(1));

Upvotes: 2

Scott Naef
Scott Naef

Reputation: 177

The query command will always return a cursor so your test for null will always fail. You need to check the count the cursor contains using cursor.getCount()

Upvotes: 0

Related Questions