Android Projects

Android Development Books

Saturday

Android Tutorial: Search the List Item



This is a sample program which shows how to implement the search functionality in android.
Underlying Algorithm:
Basic description of algorithm in step by step form:
1.) Create a Project SearchInterfaceDemo.
2.) Put the following code in main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
        <TextView
                android:id="@+id/selection"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
        />
        <ListView
                android:id="@android:id/list"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:drawSelectorOnTop="false"
        />
</LinearLayout>
3.) Create an abstract base class SearchInterfaceBase.java, which extends ListActivity and look like following:
package com.app.SearchInterfaceDemo; 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.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 SearchInterfaceBase 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;
TextView selection;
ArrayList<String> items=new ArrayList<String>();
@Override
public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        selection=(TextView)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));
}
}
4.) This activity takes care of everything related to showing a list of words, even loading the words out of the XML resource.
5.) Now put the following code in the main Activity SearchInterfaceDemo.java:
package com.app.SearchInterfaceDemo; import android.content.Intent;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
public class SearchInterfaceDemo extends SearchInterfaceBase {
        @Override
        ListAdapter makeMeAnAdapter(Intent intent) {
                return(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,items));
        }
}
6.) Create SearchInterface.java which also extends SearchInterfaceBase:
package com.app.SearchInterfaceDemo;
import android.app.SearchManager;
import android.content.Intent;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import java.util.ArrayList;
import java.util.List;
public class SearchInterface extends SearchInterfaceBase {
        @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);
        }
}
7.) Create SearchSuggestionProvider.java :
package com.app.SearchInterfaceDemo; import android.content.Context;
import android.content.SearchRecentSuggestionsProvider;
import android.provider.SearchRecentSuggestions;
public class SearchSuggestionProvider extends SearchRecentSuggestionsProvider {
        static SearchRecentSuggestions getBridge(Context ctxt) {
                return(new SearchRecentSuggestions(ctxt, "com.app.SearchInterfaceDemo",DATABASE_MODE_QUERIES));
        }
               
        public SearchSuggestionProvider() {
                        super();
                        setupSuggestions("com.app.SearchInterfaceDemo", DATABASE_MODE_QUERIES);
        }
}
8.) Update the manifest file AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.app.SearchInterfaceDemo"
     android:versionCode="1"
     android:versionName="1.0">
   <uses-sdk android:minSdkVersion="7" />    <application android:icon="@drawable/browser" android:label="Search">
                <activity android:label="Search Demo" android:name=".SearchInterfaceDemo">
                        <intent-filter>
                                <action android:name="android.intent.action.MAIN" />
                                <category android:name="android.intent.category.LAUNCHER" />
                        </intent-filter>
                        <meta-data android:name="android.app.default_searchable"         android:value=".SearchInterface" />
                </activity>
                <activity android:label="Search" android:launchMode="singleTop" android:name=".SearchInterface">
                        <intent-filter>
                                <action android:name="android.intent.action.SEARCH" />
                                <category android:name="android.intent.category.DEFAULT" />
                        </intent-filter>
                        <meta-data android:name="android.app.searchable" android:resource="@xml/searchable" />
                </activity>
                <provider android:authorities="com.app.SearchInterfaceDemo.SearchSuggestionProvider" android:name=".SearchSuggestionProvider" />
        </application>
</manifest>
9.) Create a folder xml inside the res and put searchable.xml and words.xml into that.
10.) Put the following code in searchable.xml:
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
        android:label="@string/Label"
        android:hint="@string/Hint"
        android:searchSuggestAuthority="com.app.SearchInterfaceDemo"
        android:searchSuggestSelection=" ? "
        android:searchSettingsDescription="@string/global"
        android:includeInGlobalSearch="true"/>
11.) Put the following code in words.xml:
<words>
        <word value="new" />
        <word value="old" />
        <word value="color" />
        <word value="parasia" />
        <word value="bhopal" />
        <word value="chhindwara" />
        <word value="chand" />
        <word value="jabalpur" />
        <word value="bareli" />
        <word value="jaipur" />
        <word value="jodhpur" />
        <word value="delhi" />
        <word value="Hamidiya" />
        <word value="itarasi" />
        <word value="baitul" />
        <word value="shikhar" />
        <word value="lalbaag" />
        <word value="nagpur" />
        <word value="ratnagiri" />
</words>
12.) Put the following code in res/values/strings.xml :
<?xml version="1.0" encoding="utf-8"?>
<resources>
                <string name="app_name">Search Demo</string>
                <string name="Label">My Search</string>
                <string name="Hint">Search</string>
                <string name="global">Search any word</string>
</resource>
13.) Put images search.png and browser.png in drawable folder.
14.) Run the application.
Steps to Create:
1.) Open Eclipse. Use the New Project Wizard and select Android Project Give the respective project name i.e. SearchInterfaceDemo. Enter following information:
Project name: SearchInterfaceDemo
Build Target: Android 2.1
Application name: SearchInterfaceDemo
Package name: app. com.app.SearchInterfaceDemo
Create Activity: SearchInterfaceDemo

Output –The final output:


Share this post
  • Share to Facebook
  • Share to Twitter
  • Share to Google+
  • Share to Stumble Upon
  • Share to Evernote
  • Share to Blogger
  • Share to Email
  • Share to Yahoo Messenger
  • More...

0 comments

Thanks for your comment

:) :-) :)) =)) :( :-( :(( :d :-d @-) :p :o :>) (o) [-( :-? (p) :-s (m) 8-) :-t :-b b-( :-# =p~ :-$ (b) (f) x-) (k) (h) (c) cheer

Related Posts Plugin for WordPress, Blogger...
© Google Android Lovers
Designed by BlogThietKe Cooperated with Duy Pham
Released under Creative Commons 3.0 CC BY-NC 3.0