-2

I tried to use this code in my DBHandler class

public int getPointsCount() {
        String countQuery = "SELECT * FROM " + TABLE_STUDENTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();
        return cursor.getCount();
    }

and I used this call in a button in main Activity, but it causes my app to crash when I click the Button

callButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
             int cn =  countStudents();
                studentNumberText.setText(cn);
            }
        });

public int countStudents (){
        DBHandler dbHandler = new DBHandler(this, null, null, 1);
        int c = dbHandler.getPointsCount();
        return c;
    }
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

1 Answers1

0

Get the table count by calling this method

public int gettablecount(){
    Cursor mCount= db.rawQuery("select count(*) from TABLENAME ", null);
    mCount.moveToFirst();
    int count= mCount.getInt(0);
    mCount.close();
    return  count;
}
Fairy
  • 3,592
  • 2
  • 27
  • 36
  • You can also select all the rows and get the cursor count. This doesn't answer why the app crashes, though – OneCricketeer Aug 22 '16 at 15:32
  • please Post your Log if app get crash – Prasannakumar kannan Aug 23 '16 at 04:06
  • I didn't post the question. Once you have enough reputation, you can comment on the question – OneCricketeer Aug 23 '16 at 04:43
  • the answer seems right to get rows count but i think my problem is the way of calling the countStudents () from main activity.. can any one prepare full example ? – Karamantina Aug 24 '16 at 08:48
  • please referlink http://www.codeproject.com/Questions/754766/this-is-my-code-for-loginDataBaseAdapter-and-DataB LoginDataBaseAdapter.class declare method gettablecount(), and initialize LoginDataBaseAdapter on MainActivity.class (LoginDataBaseAdapter loginDataBaseAdapter = new LoginDataBaseAdapter(this); int tablecount=loginDataBaseAdapter.gettablecount();) – Prasannakumar kannan Aug 24 '16 at 14:15