Getting contact name from number in Android 2.3.4

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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";
}

Answers

http://developer.android.com/reference/android/provider/Contacts.PhonesColumns.html#NUMBER http://developer.android.com/reference/android/provider/Contacts.PhonesColumns.html#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.

http://developer.android.com/reference/android/provider/ContactsContract.html http://developer.android.com/reference/android/provider/ContactsContract.html 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.)  

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/8785146/getting-contact-name-from-number-in-android-2-3-4

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils