0

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

Mat
  • 202,337
  • 40
  • 393
  • 406
user03
  • 29
  • 2
  • 5

2 Answers2

4

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());
            }
        }
Maher Abuthraa
  • 17,493
  • 11
  • 81
  • 103
tanglei
  • 347
  • 2
  • 6
1

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);
    }
tanglei
  • 347
  • 2
  • 6