I would like to retrieve the name of a contact associated with an incoming telephone number. As I process the incoming number in the broascastreceiver having a String with the name of the incoming caller would help my project greatly.
I would think this involves a query using the sql WHERE clause as a filter, but do I need to sort the contacts? An example or hint would be of great assistance.
Display Only Android Contacts with Phone Numbers. Open your Contacts app and tap the Options button (three dots), and select Contacts Manager. On the next screen, tap on Contacts to display from the menu.
ContactsContract defines an extensible database of contact-related information. Contact information is stored in a three-tier data model: A row in the Data table can store any kind of personal data, such as a phone number or email addresses. The set of data kinds that can be stored in this table is open-ended.
Although this has already been answered, but here is the complete function to get the contact name from number. Hope it will help others:
public static String getContactName(Context context, String phoneNumber) { ContentResolver cr = context.getContentResolver(); Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber)); Cursor cursor = cr.query(uri, new String[]{PhoneLookup.DISPLAY_NAME}, null, null, null); if (cursor == null) { return null; } String contactName = null; if(cursor.moveToFirst()) { contactName = cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME)); } if(cursor != null && !cursor.isClosed()) { cursor.close(); } return contactName; }
[Updating based on Marcus's comment]
You will have to ask for this permission:
<uses-permission android:name="android.permission.READ_CONTACTS"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With