jithu
jithu

Reputation: 45

pick number,email id and name from contact in android

I am working with phone contacts. I want to pick a contact from the contact list when i click the button and get all the contact information like name,email and phone number.i just got email and name of the contact ,but can't get the phone number.my code is give below.

             Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,Contacts.CONTENT_URI);
                            startActivityForResult(contactPickerIntent, PICK_CONTACT);
                     }
             });
     }

     @Override
     public void onActivityResult(int reqCode, int resultCode, Intent data) {


           if (resultCode == RESULT_OK) {
                switch (reqCode) 
                {
                case PICK_CONTACT:
                    Cursor cursor = null;
                    String email = "", name = "";
                    try {
                        Uri result = data.getData();
                        //Log.v(DEBUG_TAG, "Got a contact result: " + result.toString());

                        // get the contact id from the Uri
                        String id = result.getLastPathSegment();

                        // query for everything email
                        cursor = getContentResolver().query(Email.CONTENT_URI,  null, Email.CONTACT_ID + "=?", new String[] { id }, null);

                        int nameId = cursor.getColumnIndex(Contacts.DISPLAY_NAME);

                        int emailIdx = cursor.getColumnIndex(Email.DATA);


                        if (cursor.moveToFirst()) {
                            email = cursor.getString(emailIdx);
                            name = cursor.getString(nameId);

                        } else {
                           // Log.w(DEBUG_TAG, "No results");
                        }
                    } catch (Exception e) {
                       // Log.e(DEBUG_TAG, "Failed to get email data", e);
                    } finally {
                        if (cursor != null) {
                            cursor.close();
                        }

                        System.out.println(email);
                        System.out.println(name);
                        if (email.length() == 0 && name.length() == 0) 
                        {
                            Toast.makeText(this, "No Email for Selected Contact",Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                }

            } else {

            }
        }
}

here i can get email and name of the selected user.i need to get email,phonenumber and name of the selected user help me please.

Upvotes: 0

Views: 3674

Answers (5)

Vikas Singh
Vikas Singh

Reputation: 31

public void getContact() {
   // startActivityForResult(new Intent(getActivity(), ContactsPickerActivity.class), GET_PHONE_NUMBER);
    Intent contactPickerIntent =
            new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
    startActivityForResult(contactPickerIntent, GET_PHONE_NUMBER);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){

    super.onActivityResult(requestCode, resultCode, data);
    // See which child activity is calling us back.

    String name =null;
    String phone=null;
    String email=null;
    Toast.makeText(getActivity(),"dfg",Toast.LENGTH_SHORT).show();
    switch (requestCode) {
        case GET_PHONE_NUMBER:
            String DEBUG_TAG ="tag";
            Cursor cursor = null;
            Cursor phonecursor = null;
            Uri result = data.getData();
            String id = result.getLastPathSegment();

            cursor = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?", new String[] { id }, null);
            int phoneIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA);
            int nameIdx =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
            if (cursor.moveToFirst()) {
                while (cursor.isAfterLast() == false) {
                    phone = cursor.getString(phoneIdx);
                    name = cursor.getString(nameIdx);
                    cursor.moveToNext();
                }
            } else {
                //no results actions
            }
            email = "";
            try {

                Log.v(DEBUG_TAG, "Got a contact result: "
                        + result.toString());

                // get the contact id from the Uri


                // query for everything email
                cursor = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                        null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + "=?", new String[] { id },
                        null);

                int emailIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);

                // let's just get the first email
                if (cursor.moveToFirst()) {
                    email = cursor.getString(emailIdx);
                    Log.v(DEBUG_TAG, "Got email: " + email + " " + name + " " + phone);
                    Toast.makeText(getActivity(),email
                            +phone,Toast.LENGTH_SHORT).show();


                } else {
                    Log.w(DEBUG_TAG, "No results");
                }
            } catch (Exception e) {
                Log.e(DEBUG_TAG, "Failed to get email data", e);
            } finally {
                if (cursor != null) {
                    cursor.close();
                }}
            SingleContact sc = new SingleContact();
            sc.SetData(name,phone,email);
            sm.saveNumber(phone);
            contactlist.add(sc);
            cla.notifyDataSetChanged();
            break;

        default:
            break;
    }
}

Upvotes: 0

Roadies
Roadies

Reputation: 3329

public class GetContactsDemo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    readContacts();        
}

public void readContacts(){
     ContentResolver cr = getContentResolver();
     Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null, null, null, null);

     if (cur.getCount() > 0) {   
        while (cur.moveToNext()) {
            String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                System.out.println("name : " + name + ", ID : " + id);

                // get the phone number
                Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, 
                                       ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", 
                                       new String[]{id}, null);
                while (pCur.moveToNext()) {
                      String phone = pCur.getString(
                             pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                      System.out.println("phone" + phone);
                } 
                pCur.close();


                // get email and type

               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  
                    String email = emailCur.getString(
                                  emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                    String emailType = emailCur.getString(
                                  emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));

                  System.out.println("Email " + email + " Email Type : " + emailType);
                } 
                emailCur.close();

                // Get note.......
                String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?"; 
                String[] noteWhereParams = new String[]{id, 
                ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE}; 
                        Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, noteWhere, noteWhereParams, null); 
                if (noteCur.moveToFirst()) { 
                    String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
                  System.out.println("Note " + note);
                } 
                noteCur.close();

                //Get Postal Address....

                String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?"; 
                String[] addrWhereParams = new String[]{id, 
                    ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE}; 
                Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI, 
                            null, null, null, null); 
                while(addrCur.moveToNext()) {
                    String poBox = addrCur.getString(
                                 addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
                    String street = addrCur.getString(
                                 addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
                    String city = addrCur.getString(
                                 addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
                    String state = addrCur.getString(
                                 addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
                    String postalCode = addrCur.getString(
                                 addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
                    String country = addrCur.getString(
                                 addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
                    String type = addrCur.getString(
                                 addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));

                    // Do something with these....

                } 
                addrCur.close();

                // Get Instant Messenger.........
                String imWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?"; 
                String[] imWhereParams = new String[]{id, 
                    ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE}; 
                Cursor imCur = cr.query(ContactsContract.Data.CONTENT_URI, 
                        null, imWhere, imWhereParams, null); 
                if (imCur.moveToFirst()) { 
                    String imName = imCur.getString(
                             imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
                    String imType;
                    imType = imCur.getString(
                             imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE));
                } 
                imCur.close();

                // Get Organizations.........

                String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?"; 
                String[] orgWhereParams = new String[]{id, 
                    ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE}; 
                Cursor orgCur = cr.query(ContactsContract.Data.CONTENT_URI, 
                            null, orgWhere, orgWhereParams, null);
                if (orgCur.moveToFirst()) { 
                    String orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
                    String title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
                } 
                orgCur.close();
            }
            System.out.println("name :"+ name);
            System.out.println("name :"+ id);
        }

   }
}

}

Upvotes: 0

Miral Dhokiya
Miral Dhokiya

Reputation: 1710

I did this before, May be this help you Out :

Following is Function For Getting Contact Number

public void queryAllPhoneNumbersFromContacts(int contactId, List<ListViewEntry> content) {
        final String[] projection = new String[] {
                Phone.NUMBER,
                Phone.TYPE,
        };

        final Cursor phone = managedQuery(
                Phone.CONTENT_URI,  
                projection,
                Data.CONTACT_ID + "=?",
                new String[]{String.valueOf(contactId)},
                null);

        if(phone.moveToFirst()) {
            final int contactNumberColumnIndex = phone.getColumnIndex(Phone.NUMBER);
            final int contactTypeColumnIndex = phone.getColumnIndex(Phone.TYPE);

            while(!phone.isAfterLast()) {
                final String number = phone.getString(contactNumberColumnIndex);
                final int type = phone.getInt(contactTypeColumnIndex);
                content.add(new ListViewEntry(number, Phone.getTypeLabelResource(type),R.string.type_phone));
                phone.moveToNext();
            }

        }
        phone.close();
    }

Following is Function For Getting Email-id

    public void queryAllEmailAddressesFromContacts(int contactId, List<ListViewEntry> content) {
    final String[] projection = new String[] {
            Email.DATA,                         // use Email.ADDRESS for API-Level 11+
            Email.TYPE
    };

    final Cursor email = managedQuery(
            Email.CONTENT_URI,  
            projection,
            Data.CONTACT_ID + "=?",
            new String[]{String.valueOf(contactId)},
            null);

    if(email.moveToFirst()) {
        final int contactEmailColumnIndex = email.getColumnIndex(Email.DATA);
        final int contactTypeColumnIndex = email.getColumnIndex(Email.TYPE);

        while(!email.isAfterLast()) {
            final String address = email.getString(contactEmailColumnIndex);
            final int type = email.getInt(contactTypeColumnIndex);
            content.add(new ListViewEntry(address, Email.getTypeLabelResource(type),R.string.type_email));
            email.moveToNext();
        }

    }
    email.close();
}

string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="type_phone">Phone Number</string>
    <string name="type_email">E-Mail</string>
</resources>

Upvotes: 6

mainu
mainu

Reputation: 448

check this...

or you can do like this..

String hasPhone = cursor.getString(cursor.getColumnIndex(Contacts.HAS_PHONE_NUMBER));

                   if ( hasPhone.equalsIgnoreCase("1"))
                       hasPhone = "true";
                   else
                       hasPhone = "false" ;

                   if (Boolean.parseBoolean(hasPhone)) 
                   {
                    Cursor phones = getContentResolver().query(CommonDataKinds.Phone.CONTENT_URI, null,CommonDataKinds.Phone.CONTACT_ID +" = "+ nameId,null, null);
                    while (phones.moveToNext()) 
                    {
                      String phoneNumber = phones.getString(phones.getColumnIndex(CommonDataKinds.Phone.NUMBER));
                    }
                    phones.close();
                   }

Upvotes: 0

NaserShaikh
NaserShaikh

Reputation: 1576

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ( resultCode == RESULT_OK ){
            getContactInfo(data);
            Log.d(TAG, "name " + name + " phone " + phoneNumber );
            if (phoneNumber.length() == 0 || phoneNumber.equals("")) {
                ToastMsg.showToast(HomeActivity.this, "Number Not Avaialable");
            }
            else {
                String id = phoneNumber;
                Log.d(TAG, "phone "+id);
                if (id.contains("*") || id.contains("#")){
                    ToastMsg.showToast(HomeActivity.this, "Not Valid Number");
                }else{

                    ArrayList<ContactSetterGetter> setGet = helper.getAllContacts();

                    Log.d(TAG, "size "+setGet.size());
                    boolean isNumberAvailable = false;
                    if ( setGet.size() != 0 ) {

                        for ( int i = 0; i < setGet.size(); i++){
                            if ( PhoneNumberUtils.compare(id, setGet.get(i).getContactNumber()) ){
                                isNumberAvailable = true;
                            }
                        }

                            if (isNumberAvailable){
                                ToastMsg.showToast(HomeActivity.this, "Contact already Aailable");
                            }else{
                                helper.saveContactInfo(name, phoneNumber, address);
                                ToastMsg.showToast(HomeActivity.this, "Contact Added!");
                                displayContactsInfo();
                            }

                        }else{
                            helper.saveContactInfo(name, phoneNumber, address);
                            ToastMsg.showToast(HomeActivity.this, "Contact Added!");
                            displayContactsInfo();
                        }
                }
            }
            phoneNumber = "";
            name = "No Name";
            address = "";
        }
    }

    private void getContactInfo(Intent intent) {
        ContentResolver cr = getContentResolver();
        Cursor cursor = cr.query(intent.getData(), null, null, null, null);

        while (cursor.moveToNext()) {
            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
            Log.d(TAG, "name " + name);
            String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

            if (hasPhone.equalsIgnoreCase("1"))
                hasPhone = "true";
            else
                hasPhone = "false";

            if (Boolean.parseBoolean(hasPhone)) {
                Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                + " = " + contactId, null, null);
                while (phones.moveToNext()) {
                    phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    Log.d(TAG, "phone " + phoneNumber);
                }
                phones.close();
            }
        } 
        cursor.close();
    }

Upvotes: 0

Related Questions