4

I want to display all native contacts in a list and make user to add contacts from the list (Multiple contacts)to my application database.How to dothis can any one give me idea or share some code.. thanks in advance..

Sando
  • 1,893
  • 11
  • 29
  • 45

2 Answers2

13

I used this code on Android 2.1. It pulls down anyone who has a phone number (as defined by the String SELECTION variable) and returns a List of type Person. Person is an object that held the name and phone number of the user. You will have to implement a Person object in order to use this code, but it works perfectly:

public List<Person> getContactList(){
        ArrayList<Person> contactList = new ArrayList<Person>();

        Uri contactUri = ContactsContract.Contacts.CONTENT_URI;
        String[] PROJECTION = new String[] {
                ContactsContract.Contacts._ID,
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.Contacts.HAS_PHONE_NUMBER,
        };
        String SELECTION = ContactsContract.Contacts.HAS_PHONE_NUMBER + "='1'";
        Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, SELECTION, null, null);


        if (contacts.getCount() > 0)
        {
            while(contacts.moveToNext()) {
                Person aContact = new Person();
                int idFieldColumnIndex = 0;
                int nameFieldColumnIndex = 0;
                int numberFieldColumnIndex = 0;

                String contactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));

                nameFieldColumnIndex = contacts.getColumnIndex(PhoneLookup.DISPLAY_NAME);
                if (nameFieldColumnIndex > -1)
                {
                    aContact.setName(contacts.getString(nameFieldColumnIndex));
                }

                PROJECTION = new String[] {Phone.NUMBER};
                final Cursor phone = managedQuery(Phone.CONTENT_URI, PROJECTION, Data.CONTACT_ID + "=?", new String[]{String.valueOf(contactId)}, null);
                if(phone.moveToFirst()) {
                    while(!phone.isAfterLast())
                    {
                        numberFieldColumnIndex = phone.getColumnIndex(Phone.NUMBER);
                        if (numberFieldColumnIndex > -1)
                        {
                            aContact.setPhoneNum(phone.getString(numberFieldColumnIndex));
                            phone.moveToNext();
                            TelephonyManager mTelephonyMgr;
                            mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                            if (!mTelephonyMgr.getLine1Number().contains(aContact.getPhoneNum()))
                            {
                                contactList.add(aContact);  
                            }
                        }
                    }
                }
                phone.close();
            }

            contacts.close();
        }

        return contactList;
    }

EDIT: A rudimentary Person class:

public class Person {
    String myName = "";
    String myNumber = "";

    public String getName() {
        return myName;
    }

    public void setName(String name) {
        myName = name;
    }

    public String getPhoneNum() {
        return myNumber;
    }

    public void setPhoneNum(String number) {
        myNumber = number;
    }
}
CAA
  • 968
  • 10
  • 27
Jon
  • 2,502
  • 4
  • 21
  • 23
  • It would be great if you could share the Person class. – qwerty May 17 '12 at 23:17
  • 1
    I no longer have the code specific to this project or I have it tucked away somewhere at home. However, I wrote a rudimentary Person class that should at least work with the other code I put up. – Jon May 18 '12 at 20:41
  • I am getting a null pointer exception when I tried this.java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.contains(java.lang.CharSequence)' on a null object reference. at if (!mTelephonyMgr.getLine1Number().contains(aContact.getmMobileNo())) this line. @Jon – Sid Oct 08 '16 at 06:17
  • How did you implement it? @NajibPuthawala – Sid Oct 08 '16 at 06:18
1

This code works perfectly in android 4.2. And it works much faster, because you don't make additional query for each contact

private static final String CONTACT_ID = ContactsContract.Contacts._ID;
private static final String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
private static final String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;

private static final String PHONE_NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
private static final String PHONE_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;

public static ArrayList<Contact> getAll(Context context) {
    ContentResolver cr = context.getContentResolver();

    Cursor pCur = cr.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            new String[]{PHONE_NUMBER, PHONE_CONTACT_ID},
            null,
            null,
            null
    );
    if(pCur != null){
        if(pCur.getCount() > 0) {
            HashMap<Integer, ArrayList<String>> phones = new HashMap<>();
            while (pCur.moveToNext()) {
                Integer contactId = pCur.getInt(pCur.getColumnIndex(PHONE_CONTACT_ID));
                ArrayList<String> curPhones = new ArrayList<>();
                if (phones.containsKey(contactId)) {
                    curPhones = phones.get(contactId);
                }
                curPhones.add(pCur.getString(pCur.getColumnIndex(PHONE_CONTACT_ID)));
                phones.put(contactId, curPhones);
            }
            Cursor cur = cr.query(
                    ContactsContract.Contacts.CONTENT_URI,
                    new String[]{CONTACT_ID, DISPLAY_NAME, HAS_PHONE_NUMBER},
                    HAS_PHONE_NUMBER + " > 0",
                    null,
                    DISPLAY_NAME + " ASC");
            if (cur != null) {
                if (cur.getCount() > 0) {
                    ArrayList<Contact> contacts = new ArrayList<>();
                    while (cur.moveToNext()) {
                        int id = cur.getInt(cur.getColumnIndex(CONTACT_ID));
                        if(phones.containsKey(id)) {
                            Contact con = new Contact();
                            con.setMyId(id);
                            con.setName(cur.getString(cur.getColumnIndex(DISPLAY_NAME)));
                            con.setPhone(TextUtils.join(",", phones.get(id).toArray()));
                            contacts.add(con);
                        }
                    }
                    return contacts;
                }
                cur.close();
            }
        }
        pCur.close();
    }
    return null;
}

Class Contact is similar to class Person from the answer.

Nikita Leshchev
  • 1,784
  • 2
  • 14
  • 26
  • Why have you joined the number? It is in an array? I want a single mobile number of a contact.@Никита Лещёв – Sid Oct 08 '16 at 07:07
  • 1
    @Sid yes, this is an array, because contacts may have more than one phone number. If you want just one number, you can get first number and ignore all others or you can check "default" option of phone number. – Nikita Leshchev Oct 09 '16 at 10:13