从联系人列表中选择联系人android

时间:2015-05-20 13:24:06

标签: android sms contact

我正在创建一个短信应用程序,在撰写短信片段我开始结果的联系活动,onResultActivity得到结果。 我的代码适用于保存在手机中的联系人,但是为从Facebook提取的联系人提供nullPointerException, 我的代码是这个..

    Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
     pickContactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
   startActivityForResult(pickContactIntent, 1001);

并在onResultActivity

    if (requestCode == 1001) {
        // Make sure the request was successful
        if (resultCode == Activity.RESULT_OK) {
            // Get the URI that points to the selected contact
            Uri contactUri = data.getData();
            // We only need the NUMBER column, because there will be only one row in the result
            String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME};

            Cursor cursor = context.getContentResolver().query(contactUri, projection, null, null, null);
            cursor.moveToFirst();

            // Retrieve the phone number from the NUMBER column
            number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

            setContactBubble(name);
            // Do something with the phone number...
        }
    }

1 个答案:

答案 0 :(得分:0)

  

在onActivityResult中调用此方法

public String getNumberContacts(Intent intent) {

        String phoneNumber = "";
        Cursor cursor = getContentResolver().query(intent.getData(), null, null, null, null);
        while (cursor.moveToNext()) {
            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            int hasPhone = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

            if (hasPhone == 1) {
                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));
                    break;
                }
                phones.close();
            }
            break;
        }

        cursor.close();

        return phoneNumber;
    }