Android-SQLite: How to Count specific value from Column?

Posted by sanpatil on Stack Overflow See other posts from Stack Overflow or by sanpatil
Published on 2012-04-08T05:15:38Z Indexed on 2012/04/08 5:29 UTC
Read the original article Hit count: 104

Filed under:
|
|
|

I have two table (TABLE_EXAM,TABLE_RESULT). Here is value of my TABLE_RESULT.

result_id   exam_id   question_id   correct_answer  
  1            2            4              y     
  2            2            5              y       
  3            2            6              n         
  4            2            7              y        

I need to count how many correct_answer='y' where exam_id=2.
I try following code but it return 0.

public int calculateResult(int examId,String confirmAnswer)
{
    int correctAnswer=0;
    try
    {
        SQLiteDatabase db=this.getWritableDatabase();

         String selectQuery=("select count(correctAnswer) from result where exam_id ='" + examId + "' and correctAnswer ='" + 'y' +"'" );
        // String selectQuery=("SELECT COUNT(*)FROM result WHERE exam_id ='" + examId + "' and correctAnswer ='" + confirmAnswer +"'" );            
          Cursor cursor = db.rawQuery(selectQuery, null);
        if(cursor.moveToLast())
        {
            correctAnswer=cursor.getInt(3);
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return correctAnswer;
}

In variable confirm_answer i pass "y".
Give me some hint or reference.
Any help is appreciated.
Thanks in Advance

© Stack Overflow or respective owner

Related posts about android

Related posts about query