How to get contact name from number using like in selection in android
Here is the code which iam using
private String getContactNameFromNumber(String number) {
// define the columns I want the query to return
String[] projection = new String[] {
Contacts.Phones.DISPLAY_NAME,
Contacts.Phones.NUMBER };
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(Contacts.Phones.CONTEN开发者_C百科T_FILTER_URL, Uri.encode(number));
// query time
Cursor c = getContentResolver().query(contactUri, projection, null,
null, null);
// if the query returns 1 or more results
// return the first result
if (c.moveToFirst()) {
String name = c.getString(c
.getColumnIndex(Contacts.Phones.DISPLAY_NAME));
return name;
}
// return the original number if no match was found
return number;
}
but this code returns only number exactly equal to contact number. i want to use like statement so that even last 7 numbers matches i should be able to get the name.. how to write that..?
Retrieving Name from Phones Contacts using Phone Number
private String getContactNameFromNumber(String 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())
{
name = cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
}
return name;
//proceed as you need
}
try this
private String getContactNameFromNumber(String number) {
ContentResolver cr = getContentResolver();
String [] projection = new String []{
ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
};
String selection = ContactsContract.CommonDataKinds.Phone.NUMBER + " LIKE ? ";;
String[] selectionArgs = new String[]{"%"+number+ "%"};
Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection,
selection,
selectionArgs,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
//proceed as you need
...
}
精彩评论