Lee Ames
Lee Ames

Reputation: 349

Retrieving a Phone Number from Contacts Provider with ID, Android

I am able to retrieve the contact ID, but then later I wish to separately retrieve the phone number based on the contact ID. The code below is returning a null result for the phone number. (I do wish later to retrieve the name and phone number together and populate a view, but I am just trying to get the phone number to work first).

In my onCreate I have this code

   String phoneNum = getPhoneNumber(myID);
   TextView phoneTextView = (TextView) findViewById(R.id.textViewPhone);
   phoneTextView.setText(phoneNum);

This is the method for getPhoneNumber()

    protected String getPhoneNumber(String id) {
    ArrayList<String> phones = new ArrayList<String>();

    Cursor cursor = getContentResolver().query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            null,
            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
            new String[]{id}, null);

    while (cursor.moveToNext()) {
        phones.add(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
    }

    cursor.close();

    String phoneNum;

    phoneNum = phones.get(0);
    return phoneNum;
}//end getPhoneNumber();

}

This produces the error java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0, which I plan on creating some error handling for. But still, I am certain I have the ID from the previous code, so I don't know why the ArrayList returns null. If you would like to see that code, it is also in my onCreate:

    Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);

            if (cursor.getCount() != 0) {
                int numContacts = cursor.getCount();

                ArrayList<String> idList = new ArrayList<>();
                Random rand = new Random();
                int randomNum = rand.nextInt(numContacts);

                while (cursor.moveToNext()) {

                    String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                    idList.add(id);
                }

                myID = idList.get(randomNum);
                String myString = Integer.toString(randomNum);
                TextView myTextView = (TextView) findViewById(R.id.textViewID);
                myTextView.setText(myString);
                if (myID != null) {

                    myTextView.setText(myID);
                } else {

                    myTextView.setText("Try Again!");
                }
            } else {
                Toast.makeText(getApplicationContext(), "Your have no contacts.", Toast.LENGTH_SHORT).show();
            }
            cursor.close();

Upvotes: 1

Views: 1629

Answers (2)

Lee Ames
Lee Ames

Reputation: 349

I have not been able to successfully retrieve code based on the Contact ID - but this post gave me a clue: Retrieving a phone number with ContactsContract in Android - function doesn't work

I have altered my original code to query on DISPLAY_NAME instead and things are working now. Here is the method I am using to retrieve the phone number:

     private String retrieveContactNumber(String contactName) {

    Log.d(TAG, "Contact Name: " + contactName);

    Cursor cursorPhone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},

            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " = ? AND " +
                    ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
                    ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,

            new String[]{contactName},
            null);

    if (cursorPhone.moveToFirst()) {
        contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    }

    cursorPhone.close();

    Log.d(TAG, "Contact Phone Number: " + contactNumber);

    return contactNumber;
}

Upvotes: 0

Jaspreet Kaur
Jaspreet Kaur

Reputation: 1720

// You can fetch the Contact Number and Email With Following Methods.
String phone = getPhoneNumber(ContactId);
String email = getEmail("" + ContactId);

private String getPhoneNumber(long id) {
        String phone = null;
        Cursor phonesCursor = null;
        phonesCursor = queryPhoneNumbers(id);
        if (phonesCursor == null || phonesCursor.getCount() == 0) {
            // No valid number
            //signalError();
            return null;
        } else if (phonesCursor.getCount() == 1) {
            // only one number, call it.
            phone = phonesCursor.getString(phonesCursor
                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        } else {
            phonesCursor.moveToPosition(-1);
            while (phonesCursor.moveToNext()) {

                // Found super primary, call it.
                phone = phonesCursor.getString(phonesCursor
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                break;

            }
        }

        return phone;
    }

    private Cursor queryPhoneNumbers(long contactId) {
        ContentResolver cr = getContentResolver();
        Uri baseUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
                contactId);
        Uri dataUri = Uri.withAppendedPath(baseUri,
                ContactsContract.Contacts.Data.CONTENT_DIRECTORY);

        Cursor c = cr.query(dataUri, new String[]{ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.NUMBER,
                        ContactsContract.CommonDataKinds.Phone.IS_SUPER_PRIMARY, ContactsContract.RawContacts.ACCOUNT_TYPE,
                        ContactsContract.CommonDataKinds.Phone.TYPE,
                        ContactsContract.CommonDataKinds.Phone.LABEL},
                ContactsContract.Data.MIMETYPE + "=?",
                new String[]{ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE}, null);
        if (c != null && c.moveToFirst()) {
            return c;
        }
        return null;
    }


    private String getEmail(String id) {
        String email = "";
        ContentResolver cr = getContentResolver();
        Cursor emailCur = cr.query(
                ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                null,
                ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
                new String[]{id}, null);
        while (emailCur.moveToNext()) {
            // This would allow you get several email addresses
            // if the email addresses were stored in an array
            email = emailCur.getString(
                    emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
//          String emailType = emailCur.getString(
//                  emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
        }
        emailCur.close();
        return email;
    }

Upvotes: 1

Related Questions