Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems picking a contact with phone number and than reading the phone numbers

Calling the contact picker showing all contacts is done linke this (as stated many times here on SO):

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

I'm getting the contact name and all its phone numbers in onActivityResult with the following snippet:

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

Calling the contact picker and only show contacts with a phone number can be done like this (also found on SO):

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

If I do so, I only see those contacts in the contact picker that do have at least one phone number, which is exactly what I need. Unfortunately, with the code snippet above I only get the display name but NOT any phone numbers anymore.

Does anybody have an idea what I have to change to get the phone numbers?

Thanks in advance

like image 352
infero Avatar asked Nov 04 '22 10:11

infero


1 Answers

Change the Phone.Contact_Id in the where clausule for Phone._ID like this:

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

More details in this question.

Hope it help :)

like image 82
Jordi Coscolla Avatar answered Nov 15 '22 12:11

Jordi Coscolla