内容提供程序中的Android自定义方法获取表中的记录数?

jam*_*esc 5 database android android-contentprovider

我有一个访问我的数据库的内容提供程序,如果你需要处理记录集,这很好,但我需要一个方法来返回一个表示表中记录数的整数

该方法看起来像这样

public long getRecordCount(String TableName) {
    SQLiteDatabase mDatabase = mOpenHelper.getReadableDatabase();
    String sql = "SELECT COUNT(*) FROM " + TableName;
    SQLiteStatement statement = mDatabase.compileStatement(sql);
    long count = statement.simpleQueryForLong();
    return count;
}
Run Code Online (Sandbox Code Playgroud)

但我无法在内容提供商中找到任何使用此方法(或任何其他不返回游标的方法),那么放置此方法的最佳位置以及如何调用它?

显然,我可以选择使用托管查询选择所有记录并使用cursor.count结果,这是一个非常糟糕的选择,但这是处理这个特定需求的一种非常低效的方法

谢谢

mto*_*nig 10

您还可以简单地使用"count(*)"作为对内容提供程序URI的调用的投影,如下面的帮助方法

public static int count(Uri uri,String selection,String[] selectionArgs) {
  Cursor cursor = getContentResolver().query(uri,new String[] {"count(*)"},
      selection, selectionArgs, null);
  if (cursor.getCount() == 0) {
    cursor.close();
    return 0;
  } else {
    cursor.moveToFirst();
    int result = cursor.getInt(0);
    cursor.close();
    return result;
  }
}
Run Code Online (Sandbox Code Playgroud)