Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Retrieve contact name from phone number

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.

like image 923
Noah Seidman Avatar asked Jun 20 '10 13:06

Noah Seidman


People also ask

How do I show contact names and numbers on Android?

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.

What is ContactsContract?

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.


1 Answers

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"/>

like image 81
Vikram.exe Avatar answered Sep 28 '22 02:09

Vikram.exe