Last active
December 14, 2015 04:59
-
-
Save srivastavarobin/5032179 to your computer and use it in GitHub Desktop.
Function to return the name for the given contact number in Android
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This method takes the phone number as input and returns the name of the contact from default contact list if it | |
* is available | |
* | |
* @param phoneNumberPrefix | |
* : The country code. It can be left null or empty | |
* @param phoneNumber | |
* : The phone number. It can also accept country code prefixed with itself. | |
* | |
* @return: Corresponding name if available otherwise returns null | |
*/ | |
public String getContactName(String phoneNumberPrefix, String phoneNumber) { | |
String name = null; | |
Cursor cursor = null; | |
// Concatenate the phone number with the prefix | |
if (!TextUtils.isEmpty(phoneNumberPrefix)) { | |
phoneNumber = phoneNumberPrefix + phoneNumber; | |
} | |
try { | |
if (context != null) { | |
// Initialize the variables | |
ContentResolver cr = context.getContentResolver(); | |
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber)); | |
// Run the query | |
cursor = cr.query(uri, new String[] { PhoneLookup.DISPLAY_NAME }, null, null, null); | |
if (cursor != null && cursor.moveToFirst()) { | |
do { | |
name = cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME)); | |
if (!TextUtils.isEmpty(name)) { | |
break; | |
} | |
} while (cursor.moveToNext()); | |
} | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} finally { | |
attemptToCloseCursor(cursor); | |
} | |
return name; | |
} | |
/** | |
* Closes the given cursor | |
* | |
* @param cursor | |
*/ | |
private void attemptToCloseCursor(Cursor cursor) { | |
try { | |
if (cursor != null) { | |
cursor.close(); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment