Getting Number from Contacts Picker

14,529

Solution 1

@Override  
protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    if (resultCode == RESULT_OK) {  
        switch (requestCode) {  
        case CONTACT_PICKER_RESULT:
            final EditText phoneInput = (EditText) findViewById(R.id.phoneNumberInput);
            Cursor cursor = null;  
            String phoneNumber = "";
            List<String> allNumbers = new ArrayList<String>();
            int phoneIdx = 0;
            try {  
                Uri result = data.getData();  
                String id = result.getLastPathSegment();  
                cursor = getContentResolver().query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + "=?", new String[] { id }, null);  
                phoneIdx = cursor.getColumnIndex(Phone.DATA);
                if (cursor.moveToFirst()) {
                    while (cursor.isAfterLast() == false) {
                        phoneNumber = cursor.getString(phoneIdx);
                        allNumbers.add(phoneNumber);
                        cursor.moveToNext();
                    }
                } else {
                    //no results actions
                }  
            } catch (Exception e) {  
               //error actions
            } finally {  
                if (cursor != null) {  
                    cursor.close();
                }

                final CharSequence[] items = allNumbers.toArray(new String[allNumbers.size()]);
                AlertDialog.Builder builder = new AlertDialog.Builder(your_class.this);
                builder.setTitle("Choose a number");
                builder.setItems(items, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        String selectedNumber = items[item].toString();
                        selectedNumber = selectedNumber.replace("-", "");
                        phoneInput.setText(selectedNumber);
                    }
                });
                AlertDialog alert = builder.create();
                if(allNumbers.size() > 1) {
                    alert.show();
                } else {
                    String selectedNumber = phoneNumber.toString();
                    selectedNumber = selectedNumber.replace("-", "");
                    phoneInput.setText(selectedNumber);
                }

                if (phoneNumber.length() == 0) {  
                    //no numbers found actions  
                }  
            }  
            break;  
        }  
    } else {
       //activity result error actions
    }  
}

You need to adapt this to work with your app

Solution 2

I dint get that line case CONTACT_PICKER_RESULT...the code i used above using this

int PICK_CONTACT;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b=(Button) findViewById(R.id.button1);
         et=(EditText) findViewById(R.id.editText1);
        b.setOnClickListener(this);
        //et.setOnClickListener(this);

            }

@Override
public void onClick(View v) {
    switch(v.getId())
    {
    case R.id.button1:
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
        startActivityForResult(intent, PICK_CONTACT);

        break;
   // case R.id.editText1:



      //  break;

    }

Solution 3

 Intent intent = new Intent(Intent.ACTION_PICK);
 intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
 startActivityForResult(intent, PICK_CONTACT); 

These code helps u ,I think the PICK activity only returns the ID of the contact picked. From that you could query the Contact provider and if there are multiple phone numbers, prompt the user to select one of them.

U can use this also

@Override  
protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    if (resultCode == RESULT_OK) {  
    switch (requestCode) {  
    case CONTACT_PICKER_RESULT:
        final EditText phoneInput = (EditText) findViewById(R.id.phoneNumberInput);
        Cursor cursor = null;  
        String phoneNumber = "";
        List<String> allNumbers = new ArrayList<String>();
        int phoneIdx = 0;
        try {  
            Uri result = data.getData();  
            String id = result.getLastPathSegment();  
            cursor = getContentResolver().query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + "=?", new String[] { id }, null);  
            phoneIdx = cursor.getColumnIndex(Phone.DATA);
            if (cursor.moveToFirst()) {
                while (cursor.isAfterLast() == false) {
                    phoneNumber = cursor.getString(phoneIdx);
                    allNumbers.add(phoneNumber);
                    cursor.moveToNext();
                }
            } else {
                //no results actions
            }  
        } catch (Exception e) {  
           //error actions
        } finally {  
            if (cursor != null) {  
                cursor.close();
            }

            final CharSequence[] items = allNumbers.toArray(new String[allNumbers.size()]);
            AlertDialog.Builder builder = new AlertDialog.Builder(your_class.this);
            builder.setTitle("Choose a number");
            builder.setItems(items, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
                    String selectedNumber = items[item].toString();
                    selectedNumber = selectedNumber.replace("-", "");
                    phoneInput.setText(selectedNumber);
                }
            });
            AlertDialog alert = builder.create();
            if(allNumbers.size() > 1) {
                alert.show();
            } else {
                String selectedNumber = phoneNumber.toString();
                selectedNumber = selectedNumber.replace("-", "");
                phoneInput.setText(selectedNumber);
            }

            if (phoneNumber.length() == 0) {  
                //no numbers found actions  
            }  
        }  
        break;  
    }  
} else {
   //activity result error actions
}  
}

Solution 4

Kind note for beginners, Don't forget to include the following permission or else it wont work

<uses-permission android:name="android.permission.READ_CONTACTS"/>

Share:
14,529
user543010
Author by

user543010

Updated on September 15, 2022

Comments

  • user543010
    user543010 over 1 year

    I am trying to get a contacts name and phone number after a user has picked a contact from the Contact Picker. I am attempting to make my application work for SDK v3 and up so I created an abstract class that would call only the API that I needed. I already have the abstract class working (it chooses the right API) and I also have the API for SDK v3,4 working. I am having problems getting the newer API that uses ContactsContract to work.

    I can get a contacts name, but the number it retrieves is always the number for the contact ID BEFORE it! Example: I have 2 contacts "John Doe" and "Jane Doe" with respective numbers "555-555-555" and "777-777-7777" added in the contacts. John Doe is ID=1 and Jane Doe is ID=2. If I attempt to get Jane Doe's number, I get John's, 555-555-5555. If I attempt to get John's, I don't get anything. The check for if (cursor.moveToNext()) fails.

    Can you please help me fix this? It is driving me crazy. I have looked at many many examples and always get the same error.

    The Intent data is the data Intent from the onActivityResult

     
    import java.util.ArrayList;

    import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.Contacts;

    class NewContactsAdapterBridge extends ContactsAdapterBridge {

    ArrayList<String> info = new ArrayList<String>(); ArrayList<String> getInfo (Activity a, Intent data) { Uri contactData = data.getData(); Cursor cursor = a.managedQuery(contactData, null, null, null, null); if (cursor.moveToFirst()) { String id = cursor.getString( cursor.getColumnIndex(ContactsContract.Contacts._ID)); String name = cursor.getString(cursor.getColumnIndexOrThrow (ContactsContract.Contacts.DISPLAY_NAME)); String hasPhoneNumber = cursor.getString(cursor.getColumnIndexOrThrow( ContactsContract.Contacts.HAS_PHONE_NUMBER)); info.add(name); if (Integer.parseInt(hasPhoneNumber) > 0) { Uri myPhoneUri = Uri.withAppendedPath( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, id); Cursor pCur = a.managedQuery( myPhoneUri, null, null, null, null); if (pCur.moveToNext()) { String number = pCur.getString( pCur.getColumnIndex (ContactsContract.CommonDataKinds.Phone.NUMBER)); info.add(number); } } } return info; } }
  • user543010
    user543010 almost 13 years
    Thank you very much. Your code was different from anything else I have found and it worked great. Also, your code to select which number is extremely helpful.
  • buggydroid
    buggydroid over 11 years
    Works like a charm. I had forgotten to add READ_CONTACTS permission and hence was not working at first, but later it's the best thing I found to pick contact. Thanks. :)
  • DuyguK
    DuyguK over 11 years
    What is CONTACT_PICKER_RESULT? I couldnt do it.
  • Akbarsha
    Akbarsha over 10 years
    where do i have to put this findViewById(R.id.phoneNumberInput) @Sathish
  • Akbarsha
    Akbarsha over 10 years
    where do i have to put this findViewById(R.id.phoneNumberInput) view in xml @Ciprian Radu
  • Sathish
    Sathish over 10 years
    anywhere you can with in onCreate() method.