How to get row count in sqlite using Android?

前端 未结 9 1816
渐次进展
渐次进展 2020-12-04 16:36

I am creating task manager. I have tasklist and I want when I click on particular tasklist name if it empty then it goes on Add Task activity but if it has 2 or 3 tasks then

9条回答
  •  半阙折子戏
    2020-12-04 16:43

    I know it is been answered long time ago, but i would like to share this also:

    This code works very well:

    SQLiteDatabase db = this.getReadableDatabase();
    long taskCount = DatabaseUtils.queryNumEntries(db, TABLE_TODOTASK);
    

    BUT what if i dont want to count all rows and i have a condition to apply?

    DatabaseUtils have another function for this: DatabaseUtils.longForQuery

    long taskCount = DatabaseUtils.longForQuery(db, "SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?",
             new String[] { String.valueOf(tasklist_Id) });
    

    The longForQuery documentation says:

    Utility method to run the query on the db and return the value in the first column of the first row.

    public static long longForQuery(SQLiteDatabase db, String query, String[] selectionArgs)
    

    It is performance friendly and save you some time and boilerplate code

    Hope this will help somebody someday :)

提交回复
热议问题