Android SearchView tutorial: EditText with phone contacts search and autosuggestion (including source code)

SearchView is available in Android 3.0+. It enables you to search for any data by means of ContentProvider. You can write your custom ContentProvider or use the existing one. For simplicity I will show how to use Android ContactsProvider.

The Goal

The goal is to buil SearchView to find contact from address book with auto suggestions:

SearchView tutorial result
SearchView tutorial result

Download my source code if you wish!

Here it is!

1. Add SearchView to activity

SearchView is aViewGroup and you can add it as any other view to your activity:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SearchViewActivity" >

    <SearchView
        android:id="@+id/searchView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true" >
    </SearchView>

    <TextView
        android:id="@+id/searchViewResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/searchView"
        android:layout_centerHorizontal="true"
        android:text="@string/hello_world" />

</RelativeLayout>

2. Create searchable.xml file

In this file you will specify the data source to search through as well as customize the SearchView. In my case I use default Android ContactsProvider. It is identified by URI:

com.android.contacts

Put this file in /res/xml/searchable.xml. This is how my searchable.xml looks like:

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/findContact"
    android:hint="@string/findContact"
    android:includeInGlobalSearch="true"
    android:queryAfterZeroResults="true"
    android:searchMode="queryRewriteFromText"
    android:searchSettingsDescription="@string/findContact"
    android:searchSuggestAuthority="com.android.contacts"
    android:searchSuggestIntentAction="android.provider.Contacts.SEARCH_SUGGESTION_CLICKED"
    android:searchSuggestIntentData="content://com.android.contacts/contacts/lookup" >

    <!-- allow green action key for search-bar and per-suggestion clicks -->
    <actionkey
        android:keycode="KEYCODE_CALL"
        android:queryActionMsg="call"
        android:suggestActionMsg="call" />

</searchable>

Watch out: you have to specify label and hint as a strings from strings.xml. Otherwise (if they are hardcoded or absent, the SearchView did not worked for me).

3. Add permission to read contacts

Add permission in AndroidManifest.xml file in order to gain access to user’s contact book:

<uses-permission android:name="android.permission.READ_CONTACTS" />

4. Use searchable.xml in your activity

To use searchable.xml in your activity, you need to add <meta-data/> tag to your AndroidManifest.xml:

<meta-data
    android:name="android.app.searchable"
    android:resource="@xml/searchable" />

To see my full AndroidManifest.xml, see the next points.

5. Setup the SearchView in Activity code

Here you have to provide the SearchManager to the SearchView and point tho this activity as Search Result Intent Handler. Create dedicated method for it and run it in onCreate():

private void setupSearchView() {
	SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
	final SearchView searchView = (SearchView) findViewById(R.id.searchView);
	SearchableInfo searchableInfo = searchManager.getSearchableInfo(getComponentName());
	searchView.setSearchableInfo(searchableInfo);
}

6. Filter SEARCH intent in your activity

SearchView generates the SEARCH intent and handling it in your activity is crucial. This will inform you about refreshing suggestion list, the event of chosing an item from that list or confirmation button press. So add this to intent filter in your activity:

<intent-filter>
    <action android:name="android.intent.action.SEARCH" />
</intent-filter>

As for now your application should work and suggest contacts from contact book. However, choosing the contact from suggestion will not work yet.

7. Add singleTop flag to activity

Now when you choose the contact from suggestion list, the activity is relaunched. To prevent it, set the launchMode to singleTop for your activity in AndroidManifest.xml:

android:launchMode="singleTop"

This is how the full AndroidManifest.xml should look like after all:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pl.looksok.searchviewdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="11" />

    <uses-permission android:name="android.permission.READ_CONTACTS" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="pl.looksok.searchviewdemo.SearchViewActivity"
            android:label="@string/app_name"
            android:launchMode="singleTop">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>

            <meta-data
                android:name="android.app.searchable"
                android:resource="@xml/searchable" />
        </activity>
    </application>
</manifest>

8. Handle suggestion pick user action

To handle contact search event you have to handle intent with particular action: search suggestion picked, or return button clicked (search request):

@Override
protected void onNewIntent(Intent intent) {
	if (ContactsContract.Intents.SEARCH_SUGGESTION_CLICKED.equals(intent.getAction())) {
		//handles suggestion clicked query
		String displayName = getDisplayNameForContact(intent);
		resultText.setText(displayName);
	} else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
		// handles a search query
		String query = intent.getStringExtra(SearchManager.QUERY);
		resultText.setText("should search for query: '" + query + "'...");
	}
}

this is how I get contact display name:

private String getDisplayNameForContact(Intent intent) {
	Cursor phoneCursor = getContentResolver().query(intent.getData(), null, null, null, null);
	phoneCursor.moveToFirst();
	int idDisplayName = phoneCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
	String name = phoneCursor.getString(idDisplayName);
	phoneCursor.close();
	return name;
}

That’s all!

Download my source code if you wish!

Here it is!

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!

31 thoughts on “Android SearchView tutorial: EditText with phone contacts search and autosuggestion (including source code)

    1. SearchView has property called startIconized or startFolded – I am not sure its name. Just browse the documentation

  1. what if i want to add the contact name in ListView rather TextView ?
    how to do that ? Any idea.. pleaseee post it soon!!

  2. what if i want to add the contact name in ListView rather TextView ?
    how to do that ? Any idea.. pleaseee post it soon!!

  3. When i search any contact, i want to add it in ListView rather showing in a textview.. because i want many contacts in my list

    1. So in this post you learn how to find contact. And how to handle it with a listView, you will find out in lestView tutorial post on my blog. Just search for it :)

      Good luck!

  4. I can’t find what i want to do :(
    Please can you help me .. i just want to show suggested names in ListView..

    1. It’s quite a lot of code to include it in a comment. And in fact it is a dupication of standard SearchView behaviour. I mean – the searchView suggestions does all of it for you already. But it is doable of course :)

  5. how i can also display the phone numbers please help me . ur code is working correct but i want to display the phone number also.

  6. i want to update/edit contact number and display name . i am trying with different solutions. i am having troubles like when i update number, the name changes to ‘2’ automatically. please help me.

      1. Thank you. My solution is when you click on popup and it has no number, it shows toast. But is it possible to hide contacts without name in search bar?
        Sorry if my question is stupid. I’m new in android.

  7. i want to provide custom suggestion in search view widget how can i do that?
    in custom suggestion i want to provide city name of country

  8. Hey thank you for the tutorial.I want to just ask that if I type something in searchview of any activity,then it has to fetch result from child of expandable list view means what code should I write in activity?

  9. Hello Jacek, thank you very much for the turorial. I implement it into a project with fragments and a Spinner instead of a resultext , I implement the code in mainActivity and add contacts and numbers into a ItemClass. When the fragment is created, it read a list of ItemClass(custom row for spinner) from the activity and create the spinner with the info. I don’t know how .notifyDataSetChanged() the adapter from activity. when I reload the fragmeeent work fine. sorry my english! . the code is big, but if you need i ‘ll send to you. thankk.

  10. this code not woork for me . i want to
    click on searchview how to display my contact list in recyclearview plz suggest…

  11. Hi there

    I have an android that comes with a physical keyboard, when I enter contacts and I want to search for a contact, he writes me a number and then writes letters, how can I solve for it to only search for letters?

Leave a reply to Bhargav Akbari Cancel reply