1

Following up on https://stackoverflow.com/a/5935434, I'm trying to get the total number of contact items from Android's address book, in the most efficient manner.

I know that we can select all contacts and then count the results as follow:

int count = 0;
var ctx = Application.Context;
var countCursor = ctx.ApplicationContext.ContentResolver.Query(
    ContactsContract.Contacts.ContentUri,
    null,
    null,
    null,
    null
);
if (countCursor != null)
{
    count = countCursor.Count;
    countCursor.Close();
}
return count;

But I was thinking that only requesting for the count would me more efficient and consume less resources from the device.

But, as in https://stackoverflow.com/a/5935434/1990692, the following code:

int count = 0;
var ctx = Application.Context;
var countCursor = ctx.ApplicationContext.ContentResolver.Query(
    ContactsContract.Contacts.ContentUri,
    new String[] { "COUNT(*) AS c" },
    null,
    null,
    null
);
if (countCursor != null) {
    countCursor.moveToFirst();
    count = countCursor.getInt(0);
    countCursor.Close();
}
return count;

does not work and throws a Java.Lang.IllegalArgumentException with the following message: Non-token detected in 'count(*) AS c'

What am I doing wrong?

I'm using Xamarin.Android hence this is c# but I assume this would be the same in java for native Android.

Fred
  • 432
  • 6
  • 8
  • You can try to change `new String[] { "COUNT(*) AS c" }` to ` new string[] { "COUNT(*) AS c" },` .According to error, the `String` has a problem. – Junior Jiang Nov 05 '18 at 08:05
  • Hmmm... is there a typo there or is it my eyes? I cannot see any difference in your second string – Fred Nov 05 '18 at 12:22
  • Aahhh... you meant `new string[]` rather than `new String[]` i.e. without a capital S? If so, that did not change anything. In c#, string is an alias for the .NET String class. See https://programmingwithmosh.com/csharp/difference-between-string-and-string-in-c/ – Fred Nov 05 '18 at 12:30
  • In native android ,this string is from Java.Lang.String.However,in xamarin the string is from System.String.string.You can see this https://i.stack.imgur.com/RNUjH.jpg" – Junior Jiang Nov 06 '18 at 01:34
  • Either way, as I said, I've tested and as expected this doesn't change anything, still the same error message – Fred Nov 06 '18 at 05:54
  • Also find that,there is a little different between native and xamarin about `Cursor` class.Maybe it can not do all things that in native android. – Junior Jiang Nov 06 '18 at 09:54

0 Answers0