【问题标题】:Problems picking a contact with phone number and than reading the phone numbers使用电话号码选择联系人而不是读取电话号码时出现问题
【发布时间】:2012-01-02 09:21:57
【问题描述】:

调用显示所有联系人的联系人选择器已完成链接(如此处所述多次):

Intent intent = new Intent( Intent.ACTION_PICK, Contacts.CONTENT_URI );
startActivityForResult( intent, REQ_CODE );

我在 onActivityResult 中使用以下 sn-p 获取联系人姓名及其所有电话号码:

public void onActivityResult( int requestCode, int resultCode, Intent intent )
{
    Uri contactUri = intent.getData();
    ContentResolver resolver = getContentResolver();
    long contactId = -1;

    // get display name from the contact
    Cursor cursor = resolver.query( contactUri,
                                    new String[] { Contacts._ID, Contacts.DISPLAY_NAME }, 
                                    null, null, null );
    if( cursor.moveToFirst() )
    {
        contactId = cursor.getLong( 0 );
        Log.i( "tag", "ContactID = " + Long.toString( contactId ) );
        Log.i( "tag", "DisplayName = " + cursor.getString( 1 ) );
    }

    // get all phone numbers with type from the contact
    cursor = resolver.query( Phone.CONTENT_URI,
                             new String[] { Phone.TYPE, Phone.NUMBER }, 
                             Phone.CONTACT_ID + "=" + contactId, null, null );
    while( cursor.moveToNext() )
    {
        Log.i( "tag", "PhoneNumber = T:" + Integer.toString( cursor.getInt( 0 ) ) + " / N:" + cursor.getString( 1 ) );
    }

调用联系人选择器并仅显示带有电话号码的联系人可以这样做(也可以在 SO 上找到):

Intent intent = new Intent( Intent.ACTION_PICK );
intent.setType( ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE );
startActivityForResult( intent, REQ_CODE );

如果这样做,我只会在联系人选择器中看到那些至少有一个电话号码的联系人,而这正是我所需要的。不幸的是,使用上面的代码 sn-p 我只能得到显示名称,而不再得到任何电话号码。

有人知道我必须更改什么才能获取电话号码吗?

提前致谢

【问题讨论】:

    标签: android contact


    【解决方案1】:

    在 where 子句中为 Phone._ID 更改 Phone.Contact_Id,如下所示:

       cursor = resolver.query( Phone.CONTENT_URI,
                                 new String[] { Phone.TYPE, Phone.NUMBER }, 
                                 Phone._ID + "=" + contactId, null, null );
        while( cursor.moveToNext() )
        {
            Log.i( "tag", "PhoneNumber = T:" + Integer.toString( cursor.getInt( 0 ) ) + " / N:" + cursor.getString( 1 ) );
        }
    

    更多详情请看question

    希望对你有帮助:)

    【讨论】:

    • 感谢您的回答乔迪。实际问题是,我的问题的 onActivityResult 方法中的第一个查询:。它返回联系人或电话的 ID,具体取决于我是否使用“intent.setType(..)”在 Intent 中设置类型。而且由于我需要两种方式来读取联系人(使用带有或不带有电话过滤器的联系人选择器),因此我必须在第一个查询中读取 Contact._ID 和 DisplayName ,这取决于它。但你的回答有帮助......再次感谢。
    猜你喜欢
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    • 2012-06-13
    • 2011-07-23
    • 2012-04-26
    • 1970-01-01
    • 2015-01-24
    相关资源
    最近更新 更多