2

When i was looking through my contacts in phone i see whatsapp number also for those who have whatsapp account.The thing which i want to do is filter my contact list and display numbers which are synced with whatsapp.I am successfully retrieving all the contact id,number and account associated with it but not displaying whatsappaccount.Only associated google account is getting displayed.Is there any way to get whatsapp contact from local phonebook itself? I used the following code:

ContentResolver cr1 = getContentResolver();
Cursor cur = cr1.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 = cr1.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
                while (pCur.moveToNext()) 
                {
                    //phoneContactList.add(name);
                    Log.i("Contact List", name);
                    Log.i("Contact List", id);
                    
                    getContactAccount(id,cr1);
                }
                pCur.close();
            }
        }
    }


public void getContactAccount(String id,ContentResolver contentResolver){
        Cursor cursor = null;
        try {
             cursor = contentResolver.query(ContactsContract.RawContacts.CONTENT_URI,
                     new String[]{ContactsContract.RawContacts.ACCOUNT_NAME, ContactsContract.RawContacts.ACCOUNT_TYPE},
                     ContactsContract.RawContacts.CONTACT_ID +"=?",
                     new String[]{String.valueOf(id)},
                     null);
             
            if (cursor != null && cursor.getCount() >0){
                cursor.moveToFirst();
                System.out.println("Account name is"+cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME)));
                System.out.println("Account type is"+cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE)));
                cursor.close();
            }
        } catch (Exception e) {
            System.out.println(""+this.getClass().getName()+","+ e.getMessage());
        } finally{
          cursor.close();
        }
    }
akhilesh0707
  • 6,709
  • 5
  • 44
  • 51
User355635
  • 31
  • 1
  • 3
  • try this http://stackoverflow.com/questions/35448250/how-to-get-only-whatsapp-contact-from-android it read only contact who is in whatsapp account... – Mansukh Ahir Feb 18 '16 at 06:02

2 Answers2

0
The MIME type for whatsapp is:  "vnd.android.cursor.item/vnd.com.whatsapp.profile"

Use the following code`:

public class MainActivity extends ActionBarActivity {


    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment implements LoaderCallbacks<Cursor>,AdapterView.OnItemClickListener {
    /*
     * Defines an array that contains column names to move from
     * the Cursor to the ListView.
     */
 
    private final static String[] FROM_COLUMNS = {
            Build.VERSION.SDK_INT
                    >= Build.VERSION_CODES.HONEYCOMB ?
                            Data.DISPLAY_NAME :
                                Data.DISPLAY_NAME
    };
    /*
     * Defines an array that contains resource ids for the layout views
     * that get the Cursor column contents. The id is pre-defined in
     * the Android framework, so it is prefaced with "android.R.id"
     */
    private final static int[] TO_IDS = {
           android.R.id.text1
    };
    // Define global mutable variables
    // Define a ListView object
    ListView mContactsList;
    // Define variables for the contact the user selects
    // The contact's _ID value
    long mContactId;
    // The contact's LOOKUP_KEY
    String mContactKey;
    // A content URI for the selected contact
    Uri mContactUri;
 // The column index for the _ID column
    private static final int CONTACT_ID_INDEX = 0;
    // The column index for the LOOKUP_KEY column
    private static final int LOOKUP_KEY_INDEX = 1;
    // Defines the text expression
    private static final String mime_type ="vnd.android.cursor.item/vnd.com.whatsapp.profile";
    private static final String SELECTION =
             Data.MIMETYPE + " = '" + mime_type + "'";
    // Defines a variable for the search string
    private String mSearchString="Gourav";
    // Defines the array to hold values that replace the ?
    private String[] mSelectionArgs = { mSearchString };
    private static final String[] PROJECTION =
        {
            Contacts._ID,
            Contacts.LOOKUP_KEY,
            Data.DISPLAY_NAME,
            Build.VERSION.SDK_INT
                    >= Build.VERSION_CODES.HONEYCOMB ?
                            Data.MIMETYPE :
                                Data.MIMETYPE 

        };
    // An adapter that binds the result Cursor to the ListView
    private SimpleCursorAdapter mCursorAdapter;

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container,
                false);
        
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
         getLoaderManager().initLoader(0, null, this);
        // Gets the ListView from the View list of the parent activity
        mContactsList = (ListView) getActivity().findViewById(R.id.list);
        // Gets a CursorAdapter
        mCursorAdapter = new SimpleCursorAdapter(
                getActivity(),
                R.layout.contact_list,
                null,
                FROM_COLUMNS, TO_IDS,
                0);
        // Sets the adapter for the ListView
        mContactsList.setAdapter(mCursorAdapter);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        // TODO Auto-generated method stub
          // Get the Cursor
        Cursor cursor = (Cursor) parent.getAdapter().getItem(position);
        // Move to the selected contact
        cursor.moveToPosition(position);
        // Get the _ID value
        mContactId = cursor.getLong(CONTACT_ID_INDEX);
        // Get the selected LOOKUP KEY
        mContactKey = cursor.getString(LOOKUP_KEY_INDEX);
        // Create the contact's content Uri
        mContactUri = Contacts.getLookupUri(mContactId, mContactKey);
        /*
         * You can use mContactUri as the content URI for retrieving
         * the details for a contact.
         */
    }

    @Override
    public android.support.v4.content.Loader<Cursor> onCreateLoader(
            int arg0, Bundle arg1) {
        // TODO Auto-generated method stub
        /*
         * Makes search string into pattern and
         * stores it in the selection array
         */
        CursorLoader cursor = null;
        mSelectionArgs[0] = "%" + mSearchString + "%";
        Log.d("ON CREATE LOADER", "ONCLREATE LOADER CALLLEd");
        try
        {
         cursor=new CursorLoader(
                getActivity(),
                Data.CONTENT_URI,
                PROJECTION,
                SELECTION,
                null,
                null
        );
        }
        catch(Exception e)
        {
            
            e.printStackTrace();
        }
        // Starts the query
        return cursor;
    }

    @Override
    public void onLoadFinished(
            android.support.v4.content.Loader<Cursor> arg0, Cursor cursor) {
        // TODO Auto-generated method stub
         Log.d("onLoadFinished", String.valueOf(cursor.getCount()));
           mCursorAdapter.swapCursor(cursor);
    }

    @Override
    public void onLoaderReset(android.support.v4.content.Loader<Cursor> arg0) {
        // TODO Auto-generated method stub
         mCursorAdapter.swapCursor(null);

    }


}

}
akhilesh0707
  • 6,709
  • 5
  • 44
  • 51
0

Use following code to get WhatsApp contacts from phonebook with associated WhatsApp number :

private void displayWhatsAppContacts() {

    final String[] projection = {
            ContactsContract.Data.CONTACT_ID,
            ContactsContract.Data.DISPLAY_NAME,
            ContactsContract.Data.MIMETYPE,
            "account_type",
            ContactsContract.Data.DATA3,
    };

    final String selection = ContactsContract.Data.MIMETYPE + " =? and account_type=?";
    final String[] selectionArgs = {
            "vnd.android.cursor.item/vnd.com.whatsapp.profile",
            "com.whatsapp"
    };

    ContentResolver cr = getContentResolver();
    Cursor c = cr.query(
            ContactsContract.Data.CONTENT_URI,
            projection,
            selection,
            selectionArgs,
            null);

    while (c.moveToNext()) {
        String id = c.getString(c.getColumnIndex(ContactsContract.Data.CONTACT_ID));
        String number = c.getString(c.getColumnIndex(ContactsContract.Data.DATA3));
        String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

        Log.v("WhatsApp", "name " +name + " - number - "+number);

    }
    Log.v("WhatsApp", "Total WhatsApp Contacts: " + c.getCount());
    c.close();
}
NehaK
  • 2,639
  • 1
  • 15
  • 31