简体   繁体   中英

Android retrieve a set of contacts similar to built in Contacts app

I'm using code like the following, and on my phone it returns 4000+ rows, but on my phone I have 295 contacts in the Contacts app.

Whats going on here? I've been reading up on the contacts database, and I'm not yet familiar enough to figure this out.

Thanks!

    final ContentResolver cr = getContentResolver();
    final Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

    List<Contact> contacts = new ArrayList<>();

    final int nameIdx = cur.getColumnIndex(DISPLAY_NAME);
    final int idIdx = cur.getColumnIndex(ContactsContract.Contacts._ID);

    while (cur.moveToNext()) {
      String name = cur.getString(nameIdx);
      String id = cur.getString(idIdx);
      contacts.add(new Contact(name, id));
    }
    cur.close();

The solution is to filter for contacts that have IN_VISIBLE_GROUP = 1.

    final String selection = String.format("%s = ?", ContactsContract.Contacts.IN_VISIBLE_GROUP);
    final String[] selectionArgs = new String[] { "1" };
    final Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, projection, selection, selectionArgs, null);

I also tried IN_DEFAULT_DIRECTORY = 1 which also worked well but is only supported on Lollipop (21) and newer.

I am had a similar problem in Android 6. Some of the contacts were not showing up when you query using

ContactsContract.Contacts.IN_VISIBLE_GROUP = 1 

Then I changed the selection to

String selection = "in_default_directory = 1"; // Aka ContactsContract.ContactsColumns.IN_DEFAULT_DIRECTORY
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor nameCursor = context.getContentResolver().query(uri, null, selection, selectionArgs, sortOrder);

Now it returns all the contacts as per Contact app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM