Get Contact by Phone number on Android

前端 未结 3 2028
刺人心
刺人心 2020-12-20 04:50

I know how I can get all contacts in Android , and how to get their phone number.

What I cant seem to figure out is how to get a contact by phone number...

T

3条回答
  •  攒了一身酷
    2020-12-20 05:29

    You can use this method to get all your contact with name,_id and no. You can call this method in your Activity.

    private void displayContacts() {
    
            ContentResolver cr = getContentResolver();
            Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                    null, null, null, null);
            if (cur.getCount() > 0) {
                while (cur.moveToNext()) {
                    String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                    String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
    
                    if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                         Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
                                     ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null);
                         while (pCur.moveToNext()) {
                             String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    
                             System.out.println("name"+name+"ph no"+phoneNo);
                             Toast.makeText(this, "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_SHORT).show();
                         } 
                    pCur.close();
                }
                }
            }
        }
    

提交回复
热议问题