Search code examples
androidandroid-contentprovider

Relationship between sms content provider and contacts


I have a big problem, the only relationship i can get between sms content provider and the contacts content provider is the phone numbers BUT the sms content provider stores numbers in a different format as compared to how the numbers are stored in the contacts content provider. hence how can I compare the numbers between the two tables since I dont see any other relationship or column that binds them. I my country the phone number format is +254728306203, this is how the sms provider store the number but the contacts provider stores it as 072-830-6203 Any help will be greatly appreciated


Solution

  • Try this (For SDK 2.0+). Let the number be in any format.. just pass it as a string...

    Add permission android.permission.READ_CONTACTS in manifest.

    /**
         * Retrieves display name for the provided contact number
         * 
         * @param context
         *            Context
         * @param number
         *            The contact number for which display name is to be retrieved
         *            form android contacts
         * @return Returns displayName for the contact if available. If display name
         *         is not available then it returns the same number
         */
        public static String getContactNameFromNumber(Context context, String number) {
            // If name is not found, number will be returned
            String contactDisplayName = number;
    
            Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
                    Uri.encode(number));
            Cursor cursor = context.getContentResolver().query(uri,
                    new String[] { PhoneLookup.DISPLAY_NAME }, null, null, null);
            if (cursor.moveToFirst()) {
                contactDisplayName = cursor.getString(cursor
                        .getColumnIndex(PhoneLookup.DISPLAY_NAME));
            }
            cursor.close();
            Log.d("GetNumber", "Retrived DisplayName for contact number:" + number
                        + " DisplayName:" + contactDisplayName);
    
            return contactDisplayName;
    
        }