Search code examples
androidandroid-sqliteandroid-contactscontactscontract

Android Content resolver Returns all accounts activated in mobile No


While trying to retrieve a contact list from android using the below code it returns multiple accounts like google/gmail, whatsapp, and soma (how many accounts are activated depends on the number content resolver returns for that much copy of contact !). Please help me to remove it.

 cursor1=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI ,null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME +" ASC");              
 startManagingCursor(cursor1);
String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID,}; 
  int[] to = {android.R.id.text1, android.R.id.text2}; 
listadapter = new SimpleCursorAdapter(getBaseContext(), android.R.layout.simple_list_item_2, cursor1, from, to);        
 setListAdapter(listadapter);

Solution

  • Simpy try the below code which has more validations and also check for if it has phone number or not. But your andorid device's contacts should be well arranged.

       private void displayContacts() {
         
          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) {
                         Cursor pCur = cr.query(
                                   ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                   null,
                                   ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
                                   new String[]{id}, null);
                         while (pCur.moveToNext()) {
                             String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                             Toast.makeText(NativeContentProvider.this, "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_SHORT).show();
                         }
                        pCur.close();
                    }
                }
            }
        }
    

    You may also get some filteration of account here like filtering out of what's app account by using this code which fetches what's app contacts from phone contacts.