Android search box

In this Android tip, I am going to show you how to implement search box in an Android application. In your Android application, you might want to display a search box at the top of the activity (typically on the action bar) to allow the user to find a word or phrase from a data source. One approach to achieve this goal is using the search dialog that is a UI component controlled by the Android system. When the user submits a word or phrase, the system sends it in an intent with the ACTION_SEARCH action to the activity that you specify to handle searches. The dialog can also provide search suggestions while the user types. To implement the search box using the search dialog component, you will follow the steps below.




Firstly, you create a searchable configuration file called searchable.xml in the res/xml folder. The root note of the xml must be <searchable>. Typically, the android:label attribute is a string resource pointing to the application name. The android:hint attribute is not required. However, it provides important clues to the user.

<?xml version="1.0" encoding="utf-8"?>

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
   android:label="@string/app_name"
   android:hint="@string/search_hint" >
</searchable>

In the xml file above, two string values are used: app_name and search_hint. They are defined in the res/values/strings.xml file.

<?xml version="1.0" encoding="utf-8"?>
<resources>

   <string name="app_name">AndroidExample</string>
   <string name="search_hint">Search</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="title_activity_search">SearchActivity</string>

</resources>


Secondly, you have to create a search activity to handle the searches based on the query submitted from another activity. In my case, I create a new activity called SearchActivity. Generally, the search results are displayed in a list so the SearchActivity should extend the ListActivity class. The layout file of the SearchActivity (activity_search.xml) must have a ListView with the android:id="@android:id/list" attribute.

<LinearLayout 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=".SearchActivity" >

   <ListView
     android:id="@android:id/list"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:layout_weight="1"
     android:drawSelectorOnTop="false"/>

</LinearLayout>


You will create another layout file called list_item.xml file in the res/layout folder. It is used as row template of the ListView.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout  
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="5dp" >
  
<TextView
     android:id="@+id/txt"
     android:layout_width="wrap_content"
     android:layout_height="match_parent"
     android:layout_marginRight="10dp"
       />

  
</RelativeLayout>
    

Thirdly, in the AndroidManifest.xml file, you must tell the system the activity to send the search query and the activity to receive the query and handle the searches using the <meta-data> element in those activities. In this example, the MainActivity sends the query and the SearchActivity receives it and handles the searches.

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

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

   <application
     android:allowBackup="true"
     android:icon="@drawable/ic_launcher"
     android:label="@string/app_name"
     android:theme="@style/AppTheme" >
     <activity
        android:name="com.example.androidexample.MainActivity"
        android:label="@string/app_name"
       >
      
        <intent-filter>
           <action android:name="android.intent.action.MAIN" />
           <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
         <!-- enable the search dialog to send searches to SearchActivity -->
     <meta-data android:name="android.app.default_searchable"
             android:value=".SearchActivity" />
        
     </activity>
    
     <activity
        android:name="com.example.androidexample.SearchActivity"
        android:label="@string/title_activity_search"
        android:launchMode="singleTop"
         >        
        <intent-filter>
         <action android:name="android.intent.action.SEARCH" />
     </intent-filter>
     <meta-data android:name="android.app.searchable"
             android:resource="@xml/searchable"/>
     </activity>
   </application>

</manifest>


By default, the search box is invisible. To make the search box visible, you must use the onSearchRequested() to invoke it. Now in the MainActivity class, you add onResume() method as shown below to invoke the search box.

public void onResume(){
super.onResume();
onSearchRequested();
}

Finally, in the SearchActivity class, you have to write code to get the intent object that contains the search query, set up a sample data source, perform the search task, and display the result in the list.
package com.example.androidexample;

import java.util.ArrayList;
import android.os.Bundle;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.view.Menu;
import android.widget.ArrayAdapter;

public class SearchActivity extends ListActivity {

ArrayList<String> datasource;
ArrayList<String> results;
ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
results=new ArrayList<String>();
setupResultList();
setupDatasource();
getQuery(getIntent());
onSearchRequested();
}

//If you set android:launchMode to "singleTop",
//intent is passed here
protected void onNewIntent(Intent intent) {
   setIntent(intent);
   getQuery(intent);
}

private void getQuery(Intent intent) {
   if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
    String query = intent.getStringExtra(SearchManager.QUERY);
    doSearch(query);
   }
}

public void doSearch(String query){
//clear the previous results to prevent duplication
results.clear();
for(String item:datasource){
if(item.contains(query))
results.add(item);
}

}

private void setupDatasource(){
//create ArrayList object
datasource=new ArrayList<String>();
//add some example data
datasource.add("abandon");
datasource.add("abate");
datasource.add("abdicate");
datasource.add("abduct");
datasource.add("babble");
datasource.add("babe");
datasource.add("cabaret");
datasource.add("cabbage");

}

private void setupResultList(){
results=new ArrayList<String>();
adapter=new ArrayAdapter<String>(this,R.layout.list_item,R.id.txt,results);
//set adapter to the ListView
setListAdapter(adapter);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search, menu);
return true;
}

}


Android-search-box

Posted by: Dara | post date: 09-27-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.