Android:联系人Picker Intent |无法实例化Uri类型

时间:2012-10-05 18:54:57

标签: android android-contacts

我正在尝试选择仅包含电话号码的联系人。我正在关注this code

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();
}

2 个答案:

答案 0 :(得分: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.
            }
        }
    }
}

答案 1 :(得分:5)

使用Uri.parse()代替。你不能直接破坏Uri