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
If you are using ContentProvider. query() a Cursor is returned. Call Cursor. getCount() to get a count of records in the returned cursor.
The ContentResolver. query() client method always returns a Cursor containing the columns specified by the query's projection for the rows that match the query's selection criteria. A Cursor object provides random read access to the rows and columns it contains.
To access the data from a content provider, URI is used as a query string. Details of different parts of Content URI: content:// – Mandatory part of the URI as it represents that the given URI is a Content URI. authority – Signifies the name of the content provider like contacts, browser, etc.
A content provider manages access to a central repository of data. You implement a provider as one or more classes in an Android application, along with elements in the manifest file. One of your classes implements a subclass ContentProvider , which is the interface between your provider and other applications.
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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With