How to Check if a contact on android phone book has whatsapp enabled?

Viewed 12540

For a given number from my address book, I need to look-up if the number has whatsapp enabled. (The idea is to choose SMS/WhatsApp for initiating a text intent)

Lets say, I have two numbers under a contact, And I need to know which one has whatsapp enabled.

The "People" app on the Nexus 4 shows both contact numbers, And also a little below has a CONNECTIONS section, which shows only the WhatsApp possible contact.

Is there a way to look up(like how People app does) ?

3 Answers

Using @idog's method, I improved code to work easier. contactID is a string variable to be passed. If contact hasn't WhatsApp returns null, otherwise returns with contactID which has been passed as variable.

public String hasWhatsapp(String contactID) {
    String rowContactId = null;
    boolean hasWhatsApp;

    String[] projection = new String[]{ContactsContract.RawContacts._ID};
    String selection = ContactsContract.Data.CONTACT_ID + " = ? AND account_type IN (?)";
    String[] selectionArgs = new String[]{contactID, "com.whatsapp"};
    Cursor cursor = getActivity().getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
    if (cursor != null) {
        hasWhatsApp = cursor.moveToNext();
        if (hasWhatsApp) {
            rowContactId = cursor.getString(0);
        }
        cursor.close();
    }
    return rowContactId;
}
public int hasWhatsApp(String contactID) {
        int whatsAppExists = 0;
        boolean hasWhatsApp;

        String[] projection = new String[]{ContactsContract.RawContacts._ID};
        String selection = ContactsContract.Data.CONTACT_ID + " = ? AND account_type IN (?)";
        String[] selectionArgs = new String[]{contactID, "com.whatsapp"};
        Cursor cursor = getActivity().getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
        if (cursor != null) {
            hasWhatsApp = cursor.moveToNext();
            if (hasWhatsApp) {
                whatsAppExists = 1;
            }
            cursor.close();
        }
        return whatsAppExists;
    }
Related