How to Create a Search Interface with Suggestion Provider in Android?

Here is source code of the Program to Demonstrate Search Interface with Suggestion Provider in Android. The program is successfully compiled and run on a Windows system using Eclipse Ide. The program output is also shown below.

When you’re ready to add search functionality to your application, Android helps you implement the user interface with either a search dialog that appears at the top of the activity window or a search widget that you can insert in your layout. Both the search dialog and the widget can deliver the user’s search query to a specific activity in your application. This way, the user can initiate a search from any activity where the search dialog or widget is available, and the system starts the appropriate activity to perform the search and present results.

Other features available for the search dialog and widget include:
1.Voice search
2.Search suggestions based on recent queries
3.Search suggestions that match actual results in your application data

To know more go to the following link-
http://developer.android.com/guide/topics/search/search-dialog.html

MainActivity.java

package com.example.searchinterface;
 
import android.content.Intent;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
 
public class MainActivty extends Search {
    @Override
    ListAdapter makeMeAnAdapter(Intent intent) {
        return(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,items));
    }
}

Search.java

advertisement
advertisement
package com.example.searchinterface;
 
import android.os.Bundle;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
 
abstract public class Search extends ListActivity {
    abstract ListAdapter makeMeAnAdapter(Intent intent);
 
    private static final int LOCAL_SEARCH_ID = Menu.FIRST + 1;
    private static final int GLOBAL_SEARCH_ID = Menu.FIRST + 2;
    EditText selection;
    ArrayList<String> items = new ArrayList<String>();
 
    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_main);
        selection = (EditText) findViewById(R.id.selection);
 
        try {
            XmlPullParser xpp = getResources().getXml(R.xml.words);
 
            while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
                if (xpp.getEventType() == XmlPullParser.START_TAG) {
                    if (xpp.getName().equals("word")) {
                        items.add(xpp.getAttributeValue(0));
                    }
                }
                xpp.next();
            }
        } catch (Throwable t) {
            Toast.makeText(this, "Request failed: " + t.toString(), 4000)
                    .show();
        }
 
        setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
        onNewIntent(getIntent());
    }
 
    @Override
    public void onNewIntent(Intent intent) {
        ListAdapter adapter = makeMeAnAdapter(intent);
        if (adapter == null) {
            finish();
        } else {
            setListAdapter(adapter);
        }
    }
 
    public void onListItemClick(ListView parent, View v, int position, long id) {
        selection.setText(parent.getAdapter().getItem(position).toString());
 
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, LOCAL_SEARCH_ID, Menu.NONE, "Local Search")
                .setIcon(android.R.drawable.ic_search_category_default);
        menu.add(Menu.NONE, GLOBAL_SEARCH_ID, Menu.NONE, "Global Search")
                .setIcon(R.drawable.search)
                .setAlphabeticShortcut(SearchManager.MENU_KEY);
 
        return (super.onCreateOptionsMenu(menu));
    }
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case LOCAL_SEARCH_ID:
            onSearchRequested();
            return (true);
 
        case GLOBAL_SEARCH_ID:
            startSearch(null, false, null, true);
            return (true);
        }
        return (super.onOptionsItemSelected(item));
    }
}

SearchInterface

package com.example.searchinterface;
 
import java.util.ArrayList;
import java.util.List;
 
import android.app.SearchManager;
import android.content.Intent;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
 
public class SearchInterface extends Search {
    @Override
    ListAdapter makeMeAnAdapter(Intent intent) {
        ListAdapter adapter=null; 
 
        if (intent.getAction().equals(Intent.ACTION_SEARCH)) {
            String query=intent.getStringExtra(SearchManager.QUERY);
            List<String> results=searchItems(query);
 
            adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,results);
            setTitle("Search : "+query);
        }
        return(adapter);
    }
 
    private List<String> searchItems(String query) {
        SearchSuggestionProvider
            .getBridge(this)
            .saveRecentQuery(query, null);
 
        List<String> results=new ArrayList<String>();
 
        for (String item : items) {
            if (item.indexOf(query)>-1) {
                results.add(item);
            }
        }
        return(results);
    }
}

SuggestionProvider

package com.example.searchinterface;
 
import android.content.Context;
import android.content.SearchRecentSuggestionsProvider;
import android.provider.SearchRecentSuggestions;
 
public class SuggestionProvider extends SearchRecentSuggestionsProvider {
    static SearchRecentSuggestions getBridge(Context ctxt) {
        return (new SearchRecentSuggestions(ctxt,
                "com.example.MainActivity", DATABASE_MODE_QUERIES));
    }
 
    public SearchSuggestionProvider() {
        super();
        setupSuggestions("com.app.SearchInterfaceDemo", DATABASE_MODE_QUERIES);
    }
}

Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <EditText
        android:id="@+id/selection"
        android:layout_width="fill_parent"
        android:layout_height="60dp" />
 
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:drawSelectorOnTop="false" />
 
</LinearLayout>

Include these two in /res/xml.
searchable.xml

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:hint="@string/Hint"
    android:includeInGlobalSearch="true"
    android:label="@string/Label"
    android:searchSettingsDescription="@string/global"
    android:searchSuggestAuthority="com.app.SearchInterfaceDemo"
    android:searchSuggestSelection=" ? "
/>

Word.xml

advertisement
<words>
 
    <word value="C" />
    <word value="gcc" />
    <word value="C++" />
    <word value="codeBlocks" />
    <word value="Java" />
    <word value="NetBeans" />
    <word value="Eclipse" />
    <word value="Android" />
    <word value="Eclipse" />
    <word value="PHP" />
    <word value="MIPS" />
    <word value="SQL" />
    <word value="SQLite" />
    <word value="XML" />
    <word value="C#" />
    <word value="Adodbe" />
    <word value="MATLAB" />
    <word value=".NET" />
    <word value="Google" />
 
</words>

Add the following in your Manifest in

<activity>
..
</activity>

Meta Data for Your Activity

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

And the following within your

<application>
....
</application>

Defining Suggestion Provider in your Application –

 
<provider
  android:name=".SearchSuggestionProvider"
  android:authorities="com.example.searchinterface.SuggestionProvider" />

searchinterface

searchinterface1

searchinterface2

suggestionprovider

Sanfoundry Global Education & Learning Series – 100+ Java Android Tutorials.

If you wish to look at all Tutorials, go to Java Android Tutorials.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.