How to get row count in sqlite using Android?

前端 未结 9 1799
渐次进展
渐次进展 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 17:07

    Do you see what the DatabaseUtils.queryNumEntries() does? It's awful! I use this.

    public int getRowNumberByArgs(Object... args) {
        String where = compileWhere(args);
        String raw = String.format("SELECT count(*) FROM %s WHERE %s;", TABLE_NAME, where);
        Cursor c = getWriteableDatabase().rawQuery(raw, null);
        try {
            return (c.moveToFirst()) ? c.getInt(0) : 0;
        } finally {
            c.close();
        }
    }
    
    0 讨论(0)
  • 2020-12-04 17:07

    Sooo simple to get row count:

    cursor = dbObj.rawQuery("select count(*) from TABLE where COLUMN_NAME = '1' ", null);
    cursor.moveToFirst();
    String count = cursor.getString(cursor.getColumnIndex(cursor.getColumnName(0)));
    
    0 讨论(0)
  • 2020-12-04 17:08

    Change your getTaskCount Method to this:

    public int getTaskCount(long tasklist_id){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor= db.rawQuery("SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?", new String[] { String.valueOf(tasklist_id) });
        cursor.moveToFirst();
        int count= cursor.getInt(0);
        cursor.close();
        return count;
    }
    

    Then, update the click handler accordingly:

    public void onItemClick(AdapterView<?> arg0, android.view.View v, int position, long id) {
        db = new TodoTask_Database(getApplicationContext());
    
        // Get task list id
        int tasklistid = adapter.getItem(position).getTaskListId();
    
        if(db.getTaskCount(tasklistid) > 0) {    
            System.out.println(c);
            Intent taskListID = new Intent(getApplicationContext(), AddTask_List.class);
            taskListID.putExtra("TaskList_ID", tasklistid);
            startActivity(taskListID);
        } else {
            Intent addTask = new Intent(getApplicationContext(), Add_Task.class);
            startActivity(addTask);
        }
    }
    
    0 讨论(0)
提交回复
热议问题