androidandroid-contactscontactscontractrawcontacts

Query Android contact to get ACCOUNT_TYPE and ACCOUNT_NAME


I am able to obtain a list of contacts and their basic information like: name. phones, emails, ims, notes, organizations for backup purposes by using ContactsContract.Contacts.CONTENT_URI for a list of Contacts and other specific URIs for different information type.

I need, in order to fully restore all the information two more fields:

ContactsContract.RawContacts.ACCOUNT_TYPE

ContactsContract.RawContacts.ACCOUNT_NAME

Can anyone guide me how to obtain this info, knowing the Contact Id from ContactsContract.Contacts.CONTENT_URI ?

Thank you


Solution

  • public ContactAccount getContactAccount(Long id,ContentResolver contentResolver) {
    
            ContactAccount account = null;
    
            Cursor cursor = null;
            try {
    
                 cursor = contentResolver.query(ContactsContract.RawContacts.CONTENT_URI,
                         new String[]{ContactsContract.RawContacts.ACCOUNT_NAME, ContactsContract.RawContacts.ACCOUNT_TYPE},
                         ContactsContract.RawContacts.CONTACT_ID +"=?",
                         new String[]{String.valueOf(id)},
                         null);
    
                if (cursor != null && cursor.getCount() >0)
                {
                    cursor.moveToFirst();
                    account = new ContactAccount();
                    account.setAccountName(cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME)));
                    account.setAccountType(cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE)));
                    cursor.close();
                }
            } catch (Exception e) {
                Utils.log(this.getClass().getName(), e.getMessage()); 
            } finally{
              cursor.close();
            }
    
            return(account);
        }