Monday, 2 January 2012

Fetch Contact Name by passing Contact Number

Description:

Below method will return Contact name from Contact Details.
If passed number is not saved with name, it will return 'Unknown'.

Required Permission.:  <uses-permission android:name="android.permission.READ_CONTACTS"/>


/**
     * Fetch Contact Name by passing Contact Number
     *
     * @param context
     * @param number
     *            = Contact Number whose Name you want from Contact Details
     * @return name = return name if it is there else return 'Unknown'
     */


    public static final String getContactNameFromNumber(Context context,
            String number) {

        String phNo = number; // phone number you already have
        String name = "Unknown";
        try {
            Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
                    Uri.encode(phNo));
            Cursor cs = context.getContentResolver()
                    .query(uri, new String[] { PhoneLookup.DISPLAY_NAME },
                            nullnullnull);
            if (cs.getCount() > 0) {
                cs.moveToFirst();
                name = cs.getString(cs.getColumnIndex(PhoneLookup.DISPLAY_NAME));
                cs.close();
            } else {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return name;
    }

No comments:

Post a Comment