Android SQLite Cursor out of bounds exception on SELECT count(*) FROM table

前端 未结 3 1224
日久生厌
日久生厌 2020-12-16 15:49

The following function is giving me an out of bounds exception...

public void count(){
    SQLiteDatabase db = table.getWritableDatabase();
    String count          


        
相关标签:
3条回答
  • 2020-12-16 16:39

    need to move the cursor to the first (and only) row

    Cursor mcursor = db.rawQuery(count, null);
    mcursor.moveToFirst();
    int icount = mcursor.getInt(0);
    
    0 讨论(0)
  • 2020-12-16 16:43

    you can use this if you want to get Number of Rows for Specific ID or Value

    public int numbersOfrows (int id) {
            SQLiteDatabase db = this.getReadableDatabase();
            int numbersOfrows = 0 ;
    
            Cursor c = db.rawQuery("select count(*) from table_name where Column_name = 'yourValue'")
            if (c.moveToFirst()){
                numbersOfrows = c.getInt(0);
            }
    
            return numbersOfrows ;
        }
    
    0 讨论(0)
  • 2020-12-16 16:48

    You missed out

    mcursor.moveToFirst();
    
    public void count(){
        SQLiteDatabase db = table.getWritableDatabase();
        String count = "SELECT count(*) FROM table";
        Cursor mcursor = db.rawQuery(count, null);
        mcursor.moveToFirst();
        int icount = mcursor.getInt(0);
        System.out.println("NUMBER IN DB: " + icount);
    }
    

    But you should use better methods for this task, like the inbuilt helpers of DatabaseUtils

    such as

    public long count() {
        return DatabaseUtils.queryNumEntries(db,'tablename');
    }
    

    You might find helpful to use DatabaseUtils.longForQuery() to get the first column long value, when you have where query for the total count. It's simpler and you do not need that bunch of work with the Cursor.

    0 讨论(0)
提交回复
热议问题