Monday, May 11, 2015

Getting Contact List Information in Adroid








In android I wanted to select contacts with phone numbers. Here is what I tried.
 
 In my activity/fragment I called...
 
Intent getContact = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI); 
startActivityForResult(getContact, CONTACT_REQUEST_CODE); 
Note the line ...
Intent getContact = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI); 
Here "ContactsContract.CommonDataKinds.Phone.CONTENT_URI" makes sure the app requests for contacts with a phone number.





 
Then I had to override my onActivityResult() to process the information. I tried to see if any of the selected 
contacts had email id stored in the contact database. 
 
 @Override    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
  
        if (requestCode == CONTACT_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                Uri contactUri = data.getData();
                // Search for these entries/columns in the DB. 
               String projection[] = {ContactsContract.CommonDataKinds.Phone._ID,
                                      ContactsContract.CommonDataKinds.Phone.NUMBER,
                                      ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME};
 
                Cursor cursor = getActivity().getContentResolver()
                        .query(contactUri, projection, null, null, null);
                if(cursor == null) {
                    Toast.makeText(this.getActivity(), "No contact matched", Toast.LENGTH_LONG).show();
                 } else if (cursor.getCount() > 1) {
                    Toast.makeText(this.getActivity(), "Too many contacts matched", Toast.LENGTH_LONG).show(); 
v                  cursor.close();
                 } else {
                    cursor.moveToFirst(); 
                    String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
 
                    String ph = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 
                    int nameIdx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME); 
                    String name = cursor.getString(nameIdx); 
                    cursor.close(); 
                    Toast.makeText(this.getActivity(), "Found contact"+name + " with phone " + ph  , Toast.LENGTH_LONG ).show();                 
                }

            }
        }

    }


For getting contacts with emails. replace ".Phone" with ".Email" everywhere.
This blog is more like a personal note. So I have not fully checked the functionality of the code.