'How do i check if a phone number is already saved on my android phone or not?

I am building an app that enables users to save and manage a list of people, with important dates such as birthdays, anniversaries, Etc. for each person.

The goal, is to send them a personalized PDF image (with their name and details), on the important day.

The problem I am having, is what to do if the user saves a person on my app, that isn't in their contact list.

In such a case, I can't send him a whatsapp message.

So, I want to add the phone number to the phone's contacts list, only if the phone number isn't already saved in the user's regular contacts list.

How do I check if phone number XXX-XXX-XXXX exists in user's contact list or not ?



Solution 1:[1]

String res = null;
    try {
        ContentResolver resolver = ctx.getContentResolver();
        Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
        Cursor c = resolver.query(uri, new String[]{PhoneLookup.DISPLAY_NAME}, null, null, null);

        if (c != null) { // cursor not null means number is found contactsTable
            if (c.moveToFirst()) {   // so now find the contact Name
                res = c.getString(c.getColumnIndex(CommonDataKinds.Phone.DISPLAY_NAME));
            }
            c.close();
        }
    } catch (Exception ex) {
        /* Ignore */
    }        
    return res;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ă–mer Seyfettin Yavuzyi?it