Search code examples
androidcontactscontactscontractandroid-contacts

Getting Number from Contacts Picker


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

Solution

  • @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