views:

989

answers:

3

Hi,

I created the following method for retrieving stored settings from the database:

public String getEntry(long rowIndex){
    String value = "";

 Cursor c = db.query(DATABASE_TABLE, new String[] {KEY_NAME, VALUE}, KEY_NAME + "=" + rowIndex, null, null, null, null);
 int columnIndex = c.getColumnIndex(VALUE);
 int rowsCount = c.getCount();
 if(rowsCount > 0){
  String value = c.getString(columnIndex);
 }

 return value;
}

On debugging I can see cursor c contains two columns and one row but when it comes to line

String value = c.getString(columnIndex);

it throws the CursorIndexOutOfBoundsException although columnIndex = 1 which should point to a valid entry.

Does anyone know what could be wrong here?

+1  A: 

I don't know your DB-Wrapper you use, but I want to make two guesses, since I know Sqlite a little.

It could either be:

1) In my wrapper and in the C-API it is necessary to make a step (or next) every time you want to retrieve data. Your exception indicates, that you are not positionated at the right row. So you could try a "next" or "step" (what so ever your DB-Wrapper understands).

2) This c.getCount() could also bring the trouble. What could getCount do, to count on a cursor? It can iterate the cursor until it is finished. When this happens, the cursor is exhausted and you only can redo the whole thing. Reading at this point will throw something you got. To prevent the problem without need to read the table twice, you should just read all rows yourself and do the count yourself. There should be means in your DB-Wrapper (like exceptions thrown or statuses), where you can check if your cursor is exhausted yet.

When I understood your DB-Wrapper right, one of these could be the problem.

Juergen
I had to add the call to moveNext(). Thaks alot!
niko
+1  A: 

You need to move the cursor to the first row with c.moveToNext() before reading the value:

public String getEntry(long rowIndex) {
    String value = "";

    Cursor c = db.query(DATABASE_TABLE, new String[] { KEY_NAME, VALUE },
            KEY_NAME + "=" + rowIndex, null, null, null, null);

    int columnIndex = c.getColumnIndex(VALUE);
    if (c.moveToNext()) {
        value = c.getString(columnIndex);
    }

    return value;
}
Pieter Kuijpers