Fetch phone book contacts information

Hi, in this tutorial i am going to tell you about how to fetch Andorid phonebook contacts.
Previously people  class was used to fetch phone book contacts, but in later versions we use ContactsContract.
(Remember that you follow these steps in proper order)

Step1:)First make the object of content resolver class(This class provides applications access to the content model.)

ContentResolver cr = getContentResolver();

Step2:)Now create a cursor which will fetch data from ContactsContract  class.

// this cursor will contain whole data
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);

Step3): Now we have all the data in the cursor so now we can fetch the required data from the cursor as follows:(in this step i am fetching all the names and the id's)


while (cur.moveToNext()) {
                String id = cur.getString(
                        cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(
                        cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));


NAME.add(name);  //all names are added in the arraylist named "NAME".
ID.add(id);  //all names are added in the arraylist named "ID".
}

Step4):Now if you want to fetch further information like phone number or email.it can be fetched as follows:
To fetch Phone numbers of all contacts:

Cursor cphon=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"="+id, null, null);

                while(cphon.moveToNext())
                { 

//all  phone numbers will be stored in the arraylist named "PHONE_NUM"                    PHONE_NUM=cphon.getString(cphon.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));                 }




To fetch Email id's of all contacts:


Cursor emailCur = cr.query(
                        ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
                        new String[]{id}, null);

                while (emailCur.moveToNext()) {
                    String email = emailCur.getString(
                            emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));

                    EMAIL_ID.add(email); //I am saving all emails in arraylist named  "EMAIL_ID"
                    String emailType = emailCur.getString(
                            emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
                }
                emailCur.close();







thats it..........................

Comments

Popular Posts