how to select unique contacts from android
Asked Answered
R

3

6

i want to select unique contacts from android only that contacts which have phone numbers. i am using this code

ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
                null, null, ContactsContract.Contacts.DISPLAY_NAME);
        // Find the ListView resource.
        mainListView = (ListView) findViewById(R.id.mainListView);

        // When item is tapped, toggle checked properties of CheckBox and
        // Planet.
        mainListView
                .setOnItemClickListener(new AdapterView.OnItemClickListener()
                {
                    public void onItemClick(AdapterView<?> parent, View item,
                            int position, long id)
                    {
                        ContactsList planet = listAdapter.getItem(position);
                        planet.toggleChecked();
                        PlanetViewHolder viewHolder = (PlanetViewHolder) item
                                .getTag();
                        viewHolder.getCheckBox().setChecked(planet.isChecked());
                    }
                });

        // Create and populate planets.
        planets = (ContactsList[]) getLastNonConfigurationInstance();
        // planets = new Planet[10];
        // planets.Add("asdf");
        ArrayList<ContactsList> planetList = new ArrayList<ContactsList>();
        String phoneNumber = null;
        String phoneType = null;

        count = cur.getCount();
        contacts = new ContactsList[count];

        if (planets == null)
        {
            if (cur.getCount() > 0)
            {
                planets = new ContactsList[cur.getCount()];
                int i = 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)
                    {
                        // Query phone here. Covered next
                        Cursor pCur = cr
                                .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                        null,
                                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                                + " = ?", new String[]
                                        { id }, null);

                        // WHILE WE HAVE CURSOR GET THE PHONE NUMERS
                        while (pCur.moveToNext())
                        {
                            // Do something with phones
                            phoneNumber = pCur
                                    .getString(pCur
                                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));

                            phoneType = pCur
                                    .getString(pCur
                                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));

                            Log.i("Pratik", name + "'s PHONE :" + phoneNumber);
                            Log.i("Pratik", "PHONE TYPE :" + phoneType);
                        }
                        pCur.close();
                    }

                    planets = new ContactsList[]
                    { new ContactsList(name, phoneNumber) };

                    contacts[i] = planets[0];
                    planetList.addAll(Arrays.asList(planets));

                    i++;
                }
            }

this code retrieve all the contacts and put the into a list. but i want unique contacts and only that which have phone no. how can i do this?? is there any method to pass some argument in query to select unique contacts only???

Regenaregency answered 22/11, 2012 at 7:25 Comment(0)
S
11

I think you mean you got duplicate record for some contacts. So you must add condition for your query. The essential part is contacts must be in visible group and have phone number.

String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
                + ("1") + "'";
        String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
                + " COLLATE LOCALIZED ASC";
cur = context.getContentResolver().query(
                ContactsContract.Contacts.CONTENT_URI, projection, selection
                        + " AND " + ContactsContract.Contacts.HAS_PHONE_NUMBER
                        + "=1", null, sortOrder);// this query only return contacts which had phone number and not duplicated

Update 20/05/2020

  suspend fun fetchContacts(): ArrayList<FriendItem> {
        val list = ArrayList<FriendItem>()
        val uri: Uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI
        val selection = ContactsContract.Contacts.HAS_PHONE_NUMBER
        val cursor: Cursor? = context.contentResolver.query(
            uri,
            arrayOf(
                ContactsContract.CommonDataKinds.Phone.NUMBER,
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone._ID,
                ContactsContract.Contacts._ID
            ),
            selection,
            null,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC"
        )

        cursor?.let {
            val nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)
            val phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
            while (cursor.moveToNext()) {
                val info = FriendItem(
                    friendName = cursor.getString(nameIndex),
                    friendPhoneNumber = cursor.getString(phoneIndex)
                )
                list.add(info)
            }
            cursor.close()
        }
        return list
    }
Stripy answered 22/11, 2012 at 9:9 Comment(4)
@Puru: I used this on Android2.2Stripy
@Jul : Is there any solution for ICS and above versions ?Yanez
@NamTrung : Sir,Can you please post the sample code of cursor inside a while loop to access the DISPLAY_NAME and NUMBERRubeola
@NamTrung The following code is not working in my case: while (cursor.moveToNext()) { final String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); final String mob = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); Rubeola
C
2

This is working for me to get contact with phone number. Here we are querying Data table, and using CONTACT_ID contact provider documentation

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {

final String ORDER_BY = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY + " ASC";

    final String[] PROJECTION = {
            ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY,
            ContactsContract.CommonDataKinds.Phone.NUMBER
    };

return new CursorLoader(
                context,
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                PROJECTION,
                null,
                null,
                ORDER_BY
        );
}
Cloudy answered 22/4, 2015 at 0:49 Comment(0)
L
1

easy way to get phonenumbers and contact names

// set as global
Set<string> phonenumbersList = new HashSet<string>();

            Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
            while (phones.moveToNext())
            {
            String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

            //contact has name number and phonenumber does not exists in list
            if ( phoneNumber != null && name != null && !phonenumbersList.contains(phoneNumber)){ 
                planets = new ContactsList[]{ new ContactsList(name, phoneNumber) };

                phonenumbersList.add(phoneNumber);
                planetList.addAll(Arrays.asList(planets));
                planetList.Add(phoneNumber, name);
            }
            }
            phones.close();
Lincolnlincolnshire answered 22/11, 2012 at 7:40 Comment(7)
i am getting phonenumber already with my code. i want to select unique contactsRegenaregency
i don't want repetitions. one phone number comes only one timeRegenaregency
but then you still could have duplicates in names, because a contact could have more phonenumbers, i will edit my post give me a secLincolnlincolnshire
yes a contact could have more numbers but a number have only one name.Regenaregency
ok see my edit, in the example you don't have duplicate phonenumbersLincolnlincolnshire
i did make a hasset which contains all phonenumbers already stored. an before you insert a new item in your list check if the phonenumber is already in the hashset. therefore you don't have any duplicate numbersLincolnlincolnshire
@Lincolnlincolnshire Sir What if one wants a Composite unique constraint to the name and phone number?Rubeola

© 2022 - 2024 — McMap. All rights reserved.