Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching second number from the contacts in Android

I am trying to fetch second number from contact. Right now I can fetch the first number. I would like to fetch second or third number on a particular contact. Is this possible?

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    if(resultCode == RESULT_OK){
        if(requestCode == RQS_PICKCONTACT){
            Uri returnUri = data.getData();
            Cursor cursor = getContentResolver().query(returnUri, null, null, null, null);

            if(cursor.moveToNext()){
                int columnIndex_ID = cursor.getColumnIndex(ContactsContract.Contacts._ID);
                String contactID = cursor.getString(columnIndex_ID);

                int columnIndex_HASPHONENUMBER = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
                String stringHasPhoneNumber = cursor.getString(columnIndex_HASPHONENUMBER);

                if(stringHasPhoneNumber.equalsIgnoreCase("1")){
                    Cursor cursorNum = getContentResolver().query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
                            null, 
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactID, 
                            null, 
                            null);

                    //Get the first phone number
                    if(cursorNum.moveToNext()){
                        int columnIndex_number = cursorNum.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                        String stringNumber = cursorNum.getString(columnIndex_number);
                        textPhone.setText(stringNumber);
                    }

Let me know!

Thanks!

like image 981
TheDevMan Avatar asked Dec 20 '25 02:12

TheDevMan


1 Answers

Your current code will give first phone-number only, to get all the phone-numbers just iterate through the cursor, it will give you all the sub-phone numbers for the given contact.

while (cursorNum.moveToNext()) {
    int columnIndex_number = cursorNum.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
    String stringNumber = cursorNum.getString(columnIndex_number);
    Log.i(TAG,"Contact number "+stringNumber);

    // do your desired task here. 

}
like image 160
Moin Ahmed Avatar answered Dec 22 '25 16:12

Moin Ahmed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!