user03
user03

Reputation: 29

Getting all contact details which have a phone numbers in Android

In android I want all contacts details which have phone numbers so what will be the better way to get this?

Upvotes: 0

Views: 2593

Answers (2)

tanglei
tanglei

Reputation: 347

Here is a utility to retrieve phone number from all contacts:

  public static void getContact(Context ctx) {
            //获得所有的联系人
            Cursor cur = ctx.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
            //循环遍历
            if (cur.moveToFirst()) {
                int idColumn = cur.getColumnIndex(ContactsContract.Contacts._ID);

                int displayNameColumn = cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
                do {
                    //获得联系人的ID号
                    String contactId = cur.getString(idColumn);
                    //获得联系人姓名
                    String disPlayName = cur.getString(displayNameColumn);
                    //查看该联系人有多少个电话号码。如果没有这返回值为0
                    int phoneCount = cur.getInt(cur
                            .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                    if (phoneCount > 0) {
                        //获得联系人的电话号码
                        Cursor phones = ctx.getContentResolver().query(
                                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                null,
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                        + " = " + contactId, null, null);
                        if (phones.moveToFirst()) {
                            do {
                                //遍历所有的电话号码
                                String phoneNumber = phones.getString(phones
                                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                Log.d("phoneNumber:",phoneNumber);
                            } while (phones.moveToNext());
                        }
                    }
                } while (cur.moveToNext());
            }
        }

Upvotes: 4

tanglei
tanglei

Reputation: 347

http://www.tanglei.name/android-get-contacts/

private void getContacts()
    {
        // Get a cursor with all people
        Cursor c = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, 
                null, null, 
                null);

        startManagingCursor(c);
        ListAdapter adapter = new SimpleCursorAdapter(this, 
                android.R.layout.simple_list_item_2, 
                c, 
                new String[] {PhoneLookup.DISPLAY_NAME,PhoneLookup._ID} ,
                new int[] {android.R.id.text1,android.R.id.text2}); 
        setListAdapter(adapter);
    }

Upvotes: 1

Related Questions