0

I am trying to get a row count from sqlite for my android application but for some reason its always returning Zero even though I have a enough amount of rows in my DB.

Here is the Code:

DatabaseConnector database1 = new DatabaseConnector(getApplicationContext());
int TotalPosts = database1.getIds();


 public int getIds()
       {
           String selectQuery = "SELECT COUNT(Pst_id) AS CountTotal FROM student_posts";           
           SQLiteDatabase database = this.dbOpenHelper.getReadableDatabase();
           Cursor c = database.rawQuery(selectQuery, null);     
           count = c.getColumnIndex("CountTotal");    
           return count;
       }

Thanks.

2
  • You are assigning a column index to the count variable. Commented Jun 18, 2013 at 13:10
  • 2
    As @brianestey says, getColumnIndex returns the position of the column in the returned data set and NOT the value of what is in that column. In your case as you are only querying for a single value, i.e., COUNT you will only get one column and it's index will always be 0. Commented Jun 18, 2013 at 13:12

2 Answers 2

10

Try like below:

public int getIds()
    {
    String selectQuery = "SELECT Pst_id FROM student_posts";           
    SQLiteDatabase database = this.dbOpenHelper.getReadableDatabase();
    Cursor c = database.rawQuery(selectQuery, null);
    c.moveToFirst();
    int total = c.getCount();
    c.close();

    return total;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much it worked :) just waiting for 6 more minutes to accept this answer :(
Don't forget to close the cursor before returning!
4

Try c.getCount()..

Reference

Hope this helps..

Comments

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.