1

Here is my simple function:

public int countCats(String tableName) {
    int catCount = 0;
    Cursor cursor = database.rawQuery("SELECT COUNT(*) FROM " + MySQLiteHelper.TABLE_CAT, null);
    if (cursor != null) {
        catCount = cursor.getColumnIndex("COUNT");
    }

    return catCount;
}

There are 11 rows int this table. But this function returns -1. How is appropriate way to handle this?

EDIT:

I have updated to this:

public int countCats(String tableName) {
    int catCount = 0;
    Cursor cursor = database.rawQuery("SELECT COUNT("+ MySQLiteHelper.COLUMN_CAT+ ") FROM " + MySQLiteHelper.TABLE_CAT, null);
    if (cursor.moveToFirst()) {
        catCount = cursor.getInt(0);
    }
    cursor.close();


    return catCount;
}

Now I get 0;

1
  • 1
    Note that if you don't know why it returns -1, you can use getColumnIndexOrThrow(String) to see what happens ("if you expect the column to exist use getColumnIndexOrThrow(String) instead, which will make the error more clear.") Commented Jan 4, 2014 at 21:48

3 Answers 3

3

You're only asking for the column index for a column COUNT that does not exist in the cursor. Hence -1 is returned.

To retrieve the count value, move the cursor to the first row and get the first column value:

if (cursor.moveToFirst()) {
    catCount = cursor.getInt(0);
}

(A COUNT(*) query will always have a result row but it's a good habit to check the result of moveToFirst() anyway.)

Sign up to request clarification or add additional context in comments.

3 Comments

I have made a small update; now I get 0. I changed code above.
Chances are that there are no rows. Elsewhere in the question you state that there are 11 - what evidence do you have to support that claim?
Ok, so code looks right, but it may be the actual table. I believe there are 11, but I am going to confirm. Thanks.
3

You forget to call

cursor.moveToFirst();

Comments

1

You are just looking for the index of the result and not the value itself.

So now you know that the value you like to know is in the first column. Now you have to go to the first row and take that value.

cursor.moveToFirst();
int count=cursor.getInt(1);

2 Comments

FYI, column indexes start at 0. (bind arg indexing starts at 1)
I wrote that from mind mixed that up with the column number given from the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.