Q:

Trouble in retrieving contact information

I want to get the contact name from a number i had tried retrieving it through a query But i am not getting the result..It is returning the number itself.....I had  already saved that number to the contacts.
The code i tried is...
public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String x = getContactNameFromNumber("+918281306132");
    System.out.println(x);
}
private String getContactNameFromNumber(String number) {
    // define the columns I want the query to return

    System.out.println("Entering into getContactNameFromNumber");
    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.CONTENT_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;
}

}
I also added a read phone state permission too. Somebody please help me to retrieve the contact name.

A:

You can try my snippet :
public static String findContactByNumber(String phoneNumber,
        ContentResolver cr) {

    Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
            Uri.encode(phoneNumber));

    String[] phoneNoProjections = { PhoneLookup._ID,
            PhoneLookup.DISPLAY_NAME };

    Cursor cursor = cr.query(lookupUri, phoneNoProjections, null, null,
            null);

    try {

        if (cursor.moveToFirst()) {

            return cursor.getString(1); //1 is the display name index. 0 is id.

        }

    } finally {

        if (cursor != null)

            cursor.close();

    }

    return null;

}

