1

I have an EditText and a Button, the button has an OnClickListener that opens the contacts list with startActivityForResult(new Intent("android.intent.action.PICK", android.provider.ContactsContract.Contacts.CONTENT_URI), 1).

If the user click on the button, it opens the contact so that they can select one, now I want to import that number to the EditText. Is there a way to do that?

Edit: The both the EditText and the button belong to a Fragment.

esQmo_
  • 1,464
  • 3
  • 18
  • 43
  • 1
    Possible duplicate of [How to get the phone number from selected contact?](http://stackoverflow.com/questions/10696593/how-to-get-the-phone-number-from-selected-contact) – Maksim Ostrovidov Mar 30 '17 at 23:43

1 Answers1

4

If you specifically need a phone number to be picked by the user, you can request for a phone-number-picker, instead of a contact-picker like you're doing.

Try this:

Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
intent.setType(CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, 1);

The intent data you'll get in return would be for a specific phone row in the Data table:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if ((requestCode == 1) && (resultCode == RESULT_OK)) {
        Cursor cursor = null;
        try {
            Uri uri = data.getData();
            cursor = getContentResolver().query(uri, new String[] { CommonDataKinds.Phone.NUMBER }, null, null, null);
            if (cursor != null && cursor.moveToNext()) {
                String phone = cursor.getString(0);
                // Do something with phone
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
marmor
  • 27,641
  • 11
  • 107
  • 150
  • I have an error on `protedcted` void onActivityResult, saying it clashes with the one in the android.support.v4.app.Fragment and I should make it public – esQmo_ Apr 02 '17 at 07:43
  • great! no problem making it public, it depends on what class you inherit – marmor Apr 02 '17 at 08:37
  • Thank you. But just wanted to know if there is a way to filter the number, e.g removing the country code and keeping the number (exemple: +33XX XX XX XXX becomes XX XX XX XXX) – esQmo_ Apr 02 '17 at 12:13
  • you need to use Google's `libphonenumber`: https://github.com/googlei18n/libphonenumber, see: http://stackoverflow.com/a/37666789/819355 (just use `PhoneNumberFormat.NATIONAL` instead of `E164`) – marmor Apr 02 '17 at 13:54