2013-12-21 60 views
0

我想檢查我的表是空的:的Android的ContentProvider/SQLiteDatabase查詢COUNT(*)

Uri uri = Uri.withAppendedPath(BASE_URI, "account"); 
Cursor countCursor = getContentResolver().query(uri, new String[] {"COUNT(*) AS COUNT_TABLE"}, null, null, null); 

這裏是我的內容提供商查詢:

public synchronized Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { 
    int uriType = sURIMatcher.match(uri); 
    SQLiteDatabase database = dbHelper.getReadableDatabase(); 
    Cursor cursor = null; 
    switch (uriType) { 
    case ACCOUNT: 
     checkColumns(projection, ACCOUNT); 
     cursor = database.query(TableAccount.TABLE_ACCOUNT, projection, selection, selectionArgs, null, null, sortOrder); 
     break; 
    case INPUT: 
     checkColumns(projection, INPUT); 
     cursor = database.query(TableInput.TABLE_INPUT, projection, selection, selectionArgs, null, null, sortOrder); 
     break; 
    case OUTPUT: 
     checkColumns(projection, OUTPUT); 
     cursor = database.query(TableOutput.TABLE_OUTPUT, projection, selection, selectionArgs, null, null, sortOrder); 
     break; 
    default: 
     throw new IllegalArgumentException("Unknown URI: " + uri); 
    } 
    cursor.setNotificationUri(getContext().getContentResolver(), uri); 
    return cursor; 
} 

但每次我得到這個錯誤的時間:

IllegalArgumentException: Unkonwn columns in projection

我不喜歡使用一個rawQuerry

回答

0

嘗試使用此方法獲取sqlite數據庫的計數。我還添加了一些where子句示例供您參考。隨時修改:

public int getCount(String param1, String param2){ 
     SQLiteDatabase db = this.getReadableDatabase(); 
     long count; 
     count = DatabaseUtils.queryNumEntries(db, "TABLE_NAME", 
       "param1=? AND param2=?", new String[]{param1, param2}); 

     db.close(); 
     return count; 
    }