Reputation: 12837
I have a content provider that accesses my database which is fine if you need to deal with record sets but I need a method to return an integer denoting the number of records in a table
The method looks like this
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;
}
But I am unable to find any way of using this (Or any other method that does not return a cursor for that matter) in a content provider so where is the best place to put this method and how to call it?
Obviously I could do the really bad option of selecting all the records with a managed query and using the cursor.count result but that is one hugely inefficient way of dealing with this specific requirement
Thanks
Upvotes: 5
Views: 4022
Reputation: 1521
You can also simply use "count(*)" as a projection in a call to your content providers URIs, as in the following helper method
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;
}
}
Upvotes: 10
Reputation: 30835
One way you can access it is by using the call() method in the ContentResolver class. I can't seem to find much about how to actually use this on google, but my guess is that you should just have your getRecordCount()
return a bundle with your result in it. Of course the easier thing to do would be something like what's described in this SO Post.
Upvotes: 1