Thursday, December 1, 2011

Implement Search interface

In this exercise, we will implement search interface on our activity, without actual searching function. When user press the Search button, a search dialog will be opened; then after user confirm search, the query will be passed to another activity ( for searching.

Implement Search interface

First we create our search activity, Simple check if the intent equal to ACTION_SEARCH and display the query only.
package com.exercise.AndroidSearch;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class MySearch extends Activity {

protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub

// Get the intent, verify the action and get the query
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);


Modify AndroidManifest.xml to add MySearch activity to handle intent of "android.intent.action.SEARCH", with meta-data with android:name="" and android:resource="@xml/searchable". xml/searchable.xml is the searchable configuration, it will be created later.
Also add meta-data in the main activity AndroidSearchActivity, with android:name="" and android:value=".MySearch". Where is the search activity we have just created.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="8" />

android:label="@string/app_name" >
android:name=".AndroidSearchActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<meta-data android:name=""
android:value=".MySearch" />
<activity android:name=".MySearch" >
<action android:name="android.intent.action.SEARCH" />
<meta-data android:name=""


Create /res/xml/searchable.xml to define our searchable configuration.
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android=""
android:label="@string/app_name" >

The main activity have no need to change in this exercise.

Download the files.


john said...

nice tutorial, thanks so much.

Can you tell me to change button icon and
when i click on button it show quickaction dialog (choice search type).

thanks so much :)

krishnan kumar said...

Thank you so much for the tutorial... Appreciate that! Now if I want to maintain the search with respect to a specific site or url.. How will I do that? For example. I want to show all videos from YouTube when the user enters a search query in the search box. How will I be able to do this? Your help will be useful to many people.. Thanks in advance.