Android Contacts – a simple Contact Selector

If you need to perform some operations with a given Android contact, a contact selector might prove useful.
For this, a few steps are involved:
– define a cursor, to access all visible contacts
– populate a listview
– add a search filter to make the selection easier
– on filter change event, refine de query cursor and update the contacts list accordingly.
As in the previous samples for the Android Contacts tutorials, special permissions must be defined in AndroidManifest.xml:



Android Contacts – Add a new Contact using ContentProvider
Android Contacts – Custom Contact column to get the LOOKUPKEY
Android Contacts – Invoke the Edit Contact Intent
Android Contacts – Searching for contacts

To start, we create a simple interface with a editext for the filter, and a listview. It’s the classic Header+Scrollable content+Footer GUI design presented here.

Initially the Listview is populated by calling the ReadContacts(String sort) function with sort=”” (so all contacts are displayed):

void ReadContacts(String sort) {
	final Uri uri = ContactsContract.Contacts.CONTENT_URI;
	final String[] projection = new String[] {
			ContactsContract.Contacts._ID,
			ContactsContract.Contacts.DISPLAY_NAME
	};
	String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1'";
	String[] selectionArgs = null;
	final String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";

	m_curContacts = managedQuery(uri, projection, selection, selectionArgs, sortOrder);
	String[] fields = new String[] {ContactsContract.Data.DISPLAY_NAME};
	m_slvAdapter = new SimpleCursorAdapter(this, 
			android.R.layout.simple_list_item_1, 
			m_curContacts,
			fields, 
			new int[] {android.R.id.text1});
	m_slvAdapter.setFilterQueryProvider(new FilterQueryProvider() {
 
		public Cursor runQuery(CharSequence constraint) {
			Log.d(LOG_TAG, "runQuery constraint:"+constraint);
			String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1'" +
				" AND "+ ContactsContract.Contacts.DISPLAY_NAME + " LIKE '%"+constraint+"%'";
			String[] selectionArgs = null;
			Cursor cur = managedQuery(uri, projection, selection, selectionArgs, sortOrder);
			return cur;
		}
	
	});
	m_lvContacts.setAdapter(m_slvAdapter); 		 
}

This function looks similar to those presented in the previous article on Android contacts. Since for the listview content we’re using a SimpleCursorAdapter, we need to define a FilterQueryProvider() . runQuery is called every time the text in the EditText changes, as a result to the callback code:

public void onTextChanged(CharSequence s, int start, int before, int count) {
	if (m_slvAdapter!=null) {
		m_slvAdapter.getFilter().filter(s);
		m_lvContacts.setAdapter(m_slvAdapter); 
	}
}

m_slvAdapter.getFilter().filter(s); results in calling runQuery – this will run another managedQuery command to only select the contacts that contain the given String (LIKE ‘%”+constraint+”%’). Easy.

To get the onTextChanged callback on the EditText, it must be set accordingly:

m_etSearch.addTextChangedListener((TextWatcher) this);

Clicking the listview items, returns the item and a few details, extracted from the current cursor:

public void onItemClick(AdapterView arg0, View v, int position, long id) {
	Cursor cursor = (Cursor) m_lvContacts.getItemAtPosition(position);
	String szDisplayName = cursor.getString(cursor.getColumnIndexOrThrow( ContactsContract.Contacts.DISPLAY_NAME));
	String szId = cursor.getString(cursor.getColumnIndexOrThrow( ContactsContract.Contacts._ID));
	int nId = cursor.getInt(cursor.getColumnIndexOrThrow( ContactsContract.Contacts._ID));
	
	Log.d(LOG_TAG, "Item click:"+position+" szId:"+szId+" nId:"+nId+" Data:"+szDisplayName);
	Toast.makeText(getBaseContext(), "Item click:"+position+" szId:"+szId+" nId:"+nId+" Data:"+szDisplayName, Toast.LENGTH_SHORT).show();
}

Easy, and works extremely quickly. The complete project source code is available here:
AndroidContactsSelector

This article has 16 Comments

  1. Android Contacts – a simple Contact Selector

    Hi Radu Motisan,

    Thanks for such a lovely tutorial.
    Is it possible to add the email-id of each contact-list along with its contact_name in each list please provide me few code if you have thanks in advance.

    Thanks
    Mintu

  2. This has helped me so much, so thank you (actually a lot of your articles have).
    One question I have, is there a way to use the textbox entry to search other contact entries, such as email address, notes and update the listview? So, for example, I have a contact with a note “bartender from dive bar” and I can’t remember their name but remember they where a bartender, or from the dive bar, I could just type in “bartender” or “dive bar” and the list would be updated with that contact (or any contact that had that in their notes).

  3. I think a simple way of doing that would be to include all the useful info in the listview, and create a filter for it.

  4. That makes sense, and I’ve tried various ways of attempting to implement other contact info, but end up with usually “get field row # column # failed” for whatever new data element I’m adding.

  5. Hi
    I have read your tutorial and it was very helpful .Can you please tell me how to search by phone number also in your existing code.

  6. Hi, Thanks for the tutorial….I want to know how to filter the contact list names according to one phone number. that means filter names of the contacts that starts with a specific 3 digits(first 3 digits of a phone number)Please help.thanks

  7. Hello! Thank you vrey much for this lesson. But i need your help. Please help me – I want found/search contact by name and by Phone number. How can search by name you wrote in this lesson. And I can not do search by Phone number. Please tell me. Thanks.

  8. I want search(filter) with multiselect option in Listview.I made the changes in SimpleCursorAdapter constrcutor but whenever i am typing something in Edittext box the selected item from Listview will get unselected. please help me..

  9. plz tell me about “m_curContacts” variable which class you have made this object ??? thanks advance 🙂

Leave a Reply