Getting Number from Contacts Picker

contact picker api
contact picker android
contact picker flutter
web contacts api
android contact picker library
android get phone number from contact list
contact number
access phone contacts from website

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

The Contact Picker API is an on-demand API that allows users to select an A voice-over-IP app could look up which phone number to call. In this article, I will tell you how to import a contact from the contact list in Android. When we want to send a message, we must import contact from the contact list. So using this article you can import contact from your contact list.

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;

    }

This tutorial shows you how to use the Android Contact Picker to let users choose a phone number from their contact book. Later we go trough how you can  This tutorial will not only show you how to launch the contact picker and get results, but also how to use those results in Android SDK 2.0 and above. Getting Started This tutorial will start out simple, but then we’ll get in to some of the technical details of using Contacts with the ContactsContract class, which was introduced in API Level 5.

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

Information available from Contact Picker or Phone Number Picker. After a user has made a selection, the following properties will be set to information:  Try the below code to pick contact: Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI); startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT); You can fetch the required information in onActivityResult as follows:

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"/>

Chrome 77 addresses this with a new Contact Picker API, which allows The only values that web apps can request (for now) are the name, phone number, and other experiences that rely on obtaining contact information. For example, to get a random number between 1 and 10, including 10, enter 1 in the first field and 10 in the second, then press "Get Random Number". Our randomizer will pick a number from 1 through 10 at random. To generate a random number between 1 and 100, do the same, but with 100 in the second field of the picker.

 switch (reqCode) {
        case (REQUEST_CODE_email):
            if (resultCode == Activity.RESULT_OK) {
                Uri contactData = data.getData();
                Cursor c = getContentResolver().query(contactData, null, null, null, null);
                if (c.moveToFirst()) {
                    String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
                    String hasNumber = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                    String num = "";
                    if (Integer.valueOf(hasNumber) == 1) {
                        Cursor numbers = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
                        while (numbers.moveToNext()) {
                            num = numbers.getString(numbers.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                            //Toast.makeText(getApplicationContext(), "Number=" + num, Toast.LENGTH_LONG).show();

                            //asdasdasdsa
                            if(getEmail(num).isEmpty()){
                                Toast.makeText(this, "Email Not Found In That Contact Try Another", Toast.LENGTH_SHORT).show();
                            }
                            else {
                                edt_email_contact.setText("" + getEmail(num));
                            }                            }
                    }
                }
                break;
            }
         case (REQUEST_CODE_number):
            if (resultCode == Activity.RESULT_OK) {
                Uri contactData = data.getData();
                Cursor c = getContentResolver().query(contactData, null, null, null, null);
                if (c.moveToFirst()) {
                    String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
                    String hasNumber = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                    String num = "";
                    if (Integer.valueOf(hasNumber) == 1) {
                        Cursor numbers = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
                        while (numbers.moveToNext()) {
                            num = numbers.getString(numbers.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            //Toast.makeText(getApplicationContext(), "Number=" + num, Toast.LENGTH_LONG).show();

                            //asdasdasdsa

                            edt_email_contact.setText("" + num);
                        }
                    }
                }
                break;
            }

    }

number. of. contacts. Until now, you used the ContactPicker class to select to select a contact from another app (through the ContactPicker class), you get a  This tool allows you to quickly pick a random name, number or other item from a list of items. Yes, the results are quite random. When you click Pick a Random item button, the tool will submit all text line by line to our server. Then it will use python random module to generate one pseudo-random number between 0 to total items.

number. of. contacts. Until now, you used the ContactPicker class to select to select a contact from another app (through the ContactPicker class), you get a  I've been googl'ed around alot to find out how I can get the phone number when the user choose a contact in the contact picker. I know how to open the contact picker.

Windows provides a contact picker .that enables the user to provide an app with Contacts namespace as follows: // Get a contact from the user ContactPicker picker physical addresses, phone numbers, job information, significant others,​  public class CustomerForm extends Activity { private final static int CONTACT_PICKER = 1; private EditText txtMailContacto; private EditText txtNombreContacto; private EditText txtTelefono; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_customer_form); txtMailContacto = (EditText) findViewById(R.id.txtMailContacto); txtTelefono = (EditText) findViewById(R.id.txtTelefono); txtNombreContacto = (EditText

You can get this information with the Contacts framework. even more advantage of the ContactsUI framework by using the contact picker. That's because none of the default contacts have phone numbers on them – yet. Android - Get phone number and email address from Contacts - FetchContactsAsync.java

Comments
  • 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.
  • 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. :)
  • What is CONTACT_PICKER_RESULT? I couldnt do it.
  • where do i have to put this findViewById(R.id.phoneNumberInput) view in xml @Ciprian Radu
  • where do i have to put this findViewById(R.id.phoneNumberInput) @Sathish
  • anywhere you can with in onCreate() method.