Reputation: 141
i try to get the name of contact using number in 2.3.4 android, but it was not working.. here i have attached my code. Kindly assist.. i have tried so many ways as posted in Stack over flow, in emulator its working but fails while runs in phone..
String[] projection = new String[] { Contacts.Phones.DISPLAY_NAME,
Contacts.Phones.NUMBER };
// encode the phone number and build the filter URI
Toast.makeText(context, "sender: "+sender, Toast.LENGTH_LONG).show();
Uri contactUri = Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL,
Uri.encode(sender));
// query time
Cursor c = context.getContentResolver().query(contactUri, projection, null,
null, null);
// if the query returns 1 or more results
// return the first result
if(c.getCount()>0){
if (c.moveToFirst()) {
name = c.getString(c.getColumnIndex(Contacts.Phones.DISPLAY_NAME));
}
}else{
name="UnKnown";
}
Upvotes: 2
Views: 1554
Reputation: 8118
You can better use cursorloaders so the main thread can't be blocked. It is otiose to get the index and then get the string.
private String getContactName(String num) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(num));
String[] projection = new String[] {ContactsContract.Contacts.DISPLAY_NAME};
CursorLoader cursorLoader = new CursorLoader(getActivity(), uri, projection, null, null,null);
Cursor c = cursorLoader.loadInBackground();
try {
if (!c.moveToFirst())
return num;
return c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
} catch (Exception e)
{
Log.e(TAG,"Error looking up the contactname." + e);
return num;
}
finally {
if (c != null)
c.close();
}
}
Upvotes: 0
Reputation: 43504
Looking at the API for Contacts.Phones.NUMBER
:
public static final String NUMBER
The phone number as the user entered it.
So the number you use in the program must be specified exactly the same (character by character) as the one in the phone book. This might be why it fails on the phone as your phone book might contain country code information like +46xxxxxxxx
.
To get around this issue use PhoneLookup
from ContactsContract
it will use an algorithm to check if the numbers are equal (also,
the constants from Contacts.Phones
are deprecated):
public static String getContactName(String num, ContentResolver cr) {
Uri u = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI Uri.encode(num));
String[] projection = new String[] { ContactsContract.Contacts.DISPLAY_NAME};
Cursor c = cr.query(u, projection, null, null, null);
try {
if (!c.moveToFirst())
return number;
int index = c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
return c.getString(index);
} finally {
if (c != null)
c.close();
}
}
(This code returns the number if no contact is found with that number.)
Upvotes: 3