7

我正在尝试仅选择带有电话号码的联系人。并且我正在关注此代码

static final int PICK_CONTACT_REQUEST = 1;  // The request code
...
private void pickContact() {
    Intent pickContactIntent = new Intent(Intent.ACTION_PICK, new Uri("content://contacts"));
    pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
    startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}

但不幸的是,它显示一个错误:Cannot instantiate the type Uri

实际上我有另一个工作代码可以完美运行,但是在选择电子邮件联系人时崩溃。我只需要电话号码。

Intent intentContact = new Intent(Intent.ACTION_PICK,
                                ContactsContract.Contacts.CONTENT_URI);
intentContact.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivityForResult(intentContact, PICK_CONTACT);

并且在onReceive(),这个方法被调用

public void getContactInfo(Intent intent) {

    ContentResolver cr = getContentResolver();
    cursor = cr.query(intent.getData(), null, null, null, null);

    while (cursor.moveToNext()) {
        String contactId = cursor.getString(cursor
                .getColumnIndex(ContactsContract.Contacts._ID));
        if (Integer
                .parseInt(cursor.getString(cursor
                        .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
            Cursor phones = getContentResolver().query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                            + " = " + contactId, null, null);
            while (phones.moveToNext()) {
                phoneNumber = phones
                        .getString(phones
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phones.close();
        } else {
            snipp.showAlertDialog(getApplicationContext(), "No Number",
                    "Cannot read number", false);
        }

    }
    cursor.close();
}
4

2 回答 2

10

这对我有用:

private void pickContact() {
    Intent pickContactIntent = new Intent( Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI );
    pickContactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
    startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}

编辑:

onActivityResult()应该是这样的:

@Override
public void onActivityResult( int requestCode, int resultCode, Intent intent ) {

    super.onActivityResult( requestCode, resultCode, intent );
    if ( requestCode == PICK_CONTACT_REQUEST ) {

        if ( resultCode == RESULT_OK ) {
                Uri pickedPhoneNumber = intent.getData();
                // handle the picked phone number in here.
            }
        }
    }
}
于 2012-10-05T19:13:59.477 回答
5

请改用 Uri.parse()。你不能直接创建一个 Uri

于 2012-10-05T19:11:53.590 回答