Eugene
Eugene

Reputation: 60184

android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1

I always get the android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1 exception in the code below. Please advice what is wrong.

public boolean Foo(String str) {

        Cursor c = dbHelper.getItemByTitle(str);
        if (c.getCount() == 0) {
            return false;
        } else {
            c.getString(1) // Irrespective of what argument put here I get this exception
            return true;
        }
    }

Upvotes: 3

Views: 2453

Answers (2)

AngeloS
AngeloS

Reputation: 5586

You can also use c.moveToFirst() to check if there is data in the query you are returning like so:

if (c.moveToFirst()) 
      return true;
else
      return false;

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500755

I haven't used Sqlite, but I suspect you need to call moveToNext() to get to the first row before asking for values:

if (!c.moveToNext()) {
    return false;
}
String value = c.getString(1);
...

Note that getCount() returns the number of rows in the result set, but the argument to getString() indicates the column number. Also note that as far as I can see from the docs, the column number here is zero-based, unlike JDBC which is one-based.

Upvotes: 6

Related Questions