查询从联系人列表中选择电话号码

时间:2017-10-23 10:08:13

标签: android contact phone-number

我在Android中遇到查询问题。

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

我在AndroidManifest.xml中放了权限

String contactNumber = "";

if (requestCode == PICK_CONTACT && resultCode == RESULT_OK) {
    Uri contctDataVar = data.getData();
    ContentResolver cr = getContentResolver();
    Cursor cursor = cr.query(contctDataVar, null, null, null, null);
    if(cursor.moveToFirst()){
        contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        String contactID = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
        String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
        if(hasPhone.equalsIgnoreCase("1")){
            Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactID, null, null );
            if(phones.moveToFirst()){
                contactNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
        }
    }
}

contactName没问题,但是

Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactID, null, null );

不工作,应用程序将被关闭。出错了什么?

1 个答案:

答案 0 :(得分:0)

以下是获取联系电话号码的完整代码

Cursor phones = activity.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);

while (phones.moveToNext())
{
    String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
    String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();