Creating Search View in Android Studio

Introduction

 
Beginning in Android 3.0, using the SearchView widget as an item in the action bar is the preferred way to provide a search in your app. Like with all items in the action bar, you can define the SearchView to show at all times, only when there is room, or as a collapsible action, that displays the SearchView as an icon initially, then takes up the entire action bar as a search field when the user clicks the icon.
 
In today's article, we will create a search view. You will be able to see this SearchView as the Action bar in your emulator.
 
Step 1
 
First, download a search icon for your search bar and name it as "search". Copy this image to the clipboard.  "res" -> "New" -> "Android resource directory". Name the directory as "drawable" and choose the type as "drawable". Paste the image in this directory.
 
Create yet another directory and name it as "raw" and choose its type as "raw". Paste that ".txt" file in this folder in which you want to perform the search. I am using a file called "definations.txt".
 
Step 2
 
To create a menu resource file: "res" -> "Menu" -> "Menu resource file". Name this file as "options_menu" and add the following code to it:
  1. <menu xmlns:android="http://schemas.android.com/apk/res/android">  
  2.   <item  
  3.       android:id="@+id/search"  
  4.       android:title="Search"  
  5.       android:icon="@drawable/search"  
  6.       android:showAsAction="collapseActionView|ifRoom"  
  7.       android:actionViewClass="android.widget.SearchView"/>  
  8.    
  9. </menu> 
Setting "showAsAction" to "collapseActionView" as in the preceding ensures collapsing and expanding the action bar is possible as and when required.
 
Step 3
 
Creating a searchable Configuration:
 
Right-click on "res" -> "New" -> "Package". Name this package as "xml". Right-click on this directory then select "New" -> "xml resource file". Name this file as "searchable" and add the following code to it:
  1. <searchable xmlns:android="http://schemas.android.com/apk/res/android"  
  2.             android:label="@string/search"  
  3.             android:hint="@string/enter" /> 
The hint will appear in the Search space.
 
Step 4
 
Add the following code to "activity_main":
  1. <TextView  
  2.         android:layout_width="wrap_content"  
  3.         android:layout_height="wrap_content"  
  4.         android:text="@string/hello_world"  
  5.         android:id="@+id/txt"/> 
Step 5
 
"strings.xml" is used is:
  1. <string name="app_name" >  
  2.   SearchViews  
  3. </string>  
  4. <string name="action_settings" >  
  5.   Settings  
  6. </string>  
  7. <string name="hello_world" >  
  8.   Hello world!  
  9. </string>  
  10. <string name="enter" >  
  11.   Enter....  
  12. </string>  
  13. <string name="search" >  
  14.   Search  
  15. </string> 
Step 6
 
Open "MainActivity" Java file and add the following code to it:
  1. package com.searchviews;  
  2.    
  3. import android.app.SearchManager;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.os.Build;  
  7. import android.os.Bundle;  
  8. import android.app.Activity;  
  9. import android.view.Menu;  
  10. import android.view.MenuInflater;  
  11. import android.view.MenuItem;  
  12. import android.widget.SearchView;  
  13. import android.widget.TextView;  
  14.    
  15. public class MainActivity extends Activity {  
  16.     Menu m;  
  17.     final Context context=this;  
  18.     @Override  
  19.     protected void onCreate(Bundle savedInstanceState) {  
  20.         super.onCreate(savedInstanceState);  
  21.         setContentView(R.layout.activity_main);  
  22.         DatabaseTable db=new DatabaseTable(this);  
  23.     }  
  24.    
  25.    
  26.     @Override  
  27.     public boolean onCreateOptionsMenu(Menu menu) {  
  28.    
  29.         MenuInflater inflater = getMenuInflater();  
  30.         inflater.inflate(R.menu.options_menu, menu);  
  31.    
  32.         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {  
  33.         SearchManager searchManager =(SearchManager) getSystemService(Context.SEARCH_SERVICE);  
  34.         SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();  
  35.         searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));  
  36.    
  37.         }  
  38.         return true;  
  39.     }  
  40.    
  41.     @Override  
  42.     public boolean onOptionsItemSelected(MenuItem item) {  
  43.         //return super.onOptionsItemSelected(item);  
  44.         switch (item.getItemId()) {  
  45.             case R.id.search:  
  46.                 onSearchRequested();  
  47.    
  48.                 return true;  
  49.             default:  
  50.                 return false;  
  51.     }  
  52. }  

In the code above, SearchView will create the search view. "onSearchRequest()"  is called when the user signals the desire to start a search.The SearchView starts an activity with the "ACTION_SEARCH" intent when a user submits a query.
 
Step 7
 
Now we will create a database from which we will perform the search. The "definations.txt" used by me contains a word and it's definition. I will be creating a virtual table having two columns, one for the word and the other for its definition.
 
Right-click on the same package then select "New" -> "Java class". Name this file as "DatabaseTable" and add the following code to it:
  1. package com.searchviews;  
  2.    
  3. import android.content.ContentValues;  
  4. import android.content.Context;  
  5. import android.content.res.Resources;  
  6. import android.database.Cursor;  
  7. import android.database.sqlite.SQLiteDatabase;  
  8. import android.database.sqlite.SQLiteOpenHelper;  
  9. import android.database.sqlite.SQLiteQueryBuilder;  
  10. import android.text.TextUtils;  
  11. import android.util.Log;  
  12.    
  13. import java.io.BufferedReader;  
  14. import java.io.IOException;  
  15. import java.io.InputStream;  
  16. import java.io.InputStreamReader;  
  17.    
  18. public class DatabaseTable {  
  19.    
  20.     private final DatabaseOpenHelper mDatabaseOpenHelper;  
  21.     private static final String TAG = "DictionaryDatabase";  
  22.     public static final String COL_WORD = "WORD";  
  23.     public static final String COL_DEFINITION = "DEFINITION";  
  24.    
  25.     private static final String DATABASE_NAME = "DICTIONARY";  
  26.     private static final String FTS_VIRTUAL_TABLE = "FTS";  
  27.     private static final int DATABASE_VERSION = 1;  
  28.    
  29.      
  30.     public DatabaseTable(Context context) {  
  31.         mDatabaseOpenHelper = new DatabaseOpenHelper(context);  
  32.     }  
  33.    
  34.     public Cursor getWordMatches(String query, String[] columns) {  
  35.         String selection = COL_WORD + " MATCH ?";  
  36.         String[] selectionArgs = new String[] {query+"*"};  
  37.    
  38.         return query(selection, selectionArgs, columns);  
  39.     }  
  40.    
  41.     private Cursor query(String selection, String[] selectionArgs, String[] columns) {  
  42.         SQLiteQueryBuilder builder = new SQLiteQueryBuilder();  
  43.         builder.setTables(FTS_VIRTUAL_TABLE);  
  44.    
  45.         Cursor cursor = builder.query(mDatabaseOpenHelper.getReadableDatabase(),  
  46.                 columns, selection, selectionArgs, nullnullnull);  
  47.    
  48.         if (cursor == null) {  
  49.             return null;  
  50.         } else if (!cursor.moveToFirst()) {  
  51.             cursor.close();  
  52.             return null;  
  53.         }  
  54.         return cursor;  
  55.     }  
  56.    
  57.     private static class DatabaseOpenHelper extends SQLiteOpenHelper{  
  58.         private final Context mHelperContext;  
  59.         private SQLiteDatabase mDatabase;  
  60.    
  61.         private static final String FTS_TABLE_CREATE =  
  62.                 "CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE +  
  63.                         " USING fts3 (" +  
  64.                         COL_WORD + ", " +  
  65.                         COL_DEFINITION + ")";  
  66.         private SQLiteOpenHelper mDatabaseOpenHelper;  
  67.    
  68.         DatabaseOpenHelper(Context context) {  
  69.             super(context, DATABASE_NAME, null, DATABASE_VERSION);  
  70.             mHelperContext = context;  
  71.         }  
  72.    
  73.         @Override  
  74.         public void onCreate(SQLiteDatabase db) {  
  75.             mDatabase = db;  
  76.             mDatabase.execSQL(FTS_TABLE_CREATE);  
  77.             loadDictionary();  
  78.         }  
  79.    
  80.         @Override  
  81.         public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  82.             Log.w(TAG, "Upgrading database from version " + oldVersion + " to "  
  83.                     + newVersion + ", which will destroy all old data");  
  84.             db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE);  
  85.             onCreate(db);  
  86.    
  87.         }  
  88.    
  89.         private void loadDictionary() {  
  90.             new Thread(new Runnable() {  
  91.                 public void run() {  
  92.                     try {  
  93.                         loadWords();  
  94.                     } catch (IOException e) {  
  95.                         throw new RuntimeException(e);  
  96.                     }  
  97.                 }  
  98.             }).start();  
  99.         }  
  100.    
  101.         private void loadWords() throws IOException {  
  102.             final Resources resources = mHelperContext.getResources();  
  103.             InputStream inputStream = resources.openRawResource(R.raw.definations);  
  104.             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));  
  105.    
  106.             try {  
  107.                 String line;  
  108.                 while ((line = reader.readLine()) != null) {  
  109.                     String[] strings = TextUtils.split(line, "-");  
  110.                     if (strings.length < 2continue;  
  111.                     long id = addWord(strings[0].trim(), strings[1].trim());  
  112.                     if (id < 0) {  
  113.                         Log.e(TAG, "unable to add word: " + strings[0].trim());  
  114.                     }  
  115.                 }  
  116.             } finally {  
  117.                 reader.close();  
  118.             }  
  119.         }  
  120.    
  121.         public long addWord(String word, String definition) {  
  122.             ContentValues initialValues = new ContentValues();  
  123.             initialValues.put(COL_WORD, word);  
  124.             initialValues.put(COL_DEFINITION, definition);  
  125.    
  126.             return mDatabase.insert(FTS_VIRTUAL_TABLE, null, initialValues);  
  127.         }  
  128.    
  129.    
  130.     }  

"getWordMatches" functions perform the major matching task.
 
Step 8
 
Now we will create our search activity. Create a Java file and name it "SearchResultsActivity". Add the following code to it:
  1. package com.searchviews;  
  2.    
  3. import android.*;  
  4. import android.R;  
  5. import android.app.Activity;  
  6. import android.app.SearchManager;  
  7. import android.content.Context;  
  8. import android.content.Intent;  
  9. import android.database.Cursor;  
  10. import android.os.Bundle;  
  11. import android.view.View;  
  12. import android.widget.AdapterView;  
  13. import android.widget.ArrayAdapter;  
  14. import android.widget.ListView;  
  15. import android.widget.TextView;  
  16.    
  17. public class SearchResultsActivity extends Activity {  
  18.     DatabaseTable db = new DatabaseTable(this);  
  19.     final Context context=this;  
  20.     ListView list;  
  21.     TextView v;  
  22.     String res;  
  23.     @Override  
  24.     protected void onCreate(Bundle savedInstanceState) {  
  25.         super.onCreate(savedInstanceState);  
  26.         setContentView(R.layout.simple_list_item_1);  
  27.         v=(TextView)findViewById(R.id.text1);  
  28.    
  29.         handleIntent(getIntent());  
  30.         v.setText(res);  
  31.    
  32.     }  
  33.    
  34.     @Override  
  35.     protected void onNewIntent(Intent intent) {  
  36.         super.onNewIntent(intent);  
  37.         handleIntent(getIntent());  
  38.     }  
  39.    
  40.     private void handleIntent(Intent intent) {  
  41.         if (Intent.ACTION_SEARCH.equals(intent.getAction())) {  
  42.             String query = intent.getStringExtra(SearchManager.QUERY);  
  43.             Cursor c = db.getWordMatches(query, null);  
  44.             c.moveToFirst();  
  45.             res=c.getString(1);  
  46.    
  47.    
  48.         }  
  49.     }  

The "onCreate" function calls the "handleIntent" function. "handleIntent" performs the search and returns the result to a Cursor. Back in "onCreate" I retrieved and printed the result of searching. The output, in this case, is the definition of the word entered.
 
Step 9
 
Now the most important part!!
 
Open "AndroidManifest" and make the following changes to it:
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.searchviews"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.    
  7.   <uses-sdk  
  8.       android:minSdkVersion="11"  
  9.       android:targetSdkVersion="15" />  
  10.    
  11.   <application  
  12.           android:allowBackup="true"  
  13.           android:icon="@drawable/ic_launcher"  
  14.           android:label="@string/app_name"  
  15.           android:theme="@style/AppTheme" >  
  16.     <activity  
  17.             android:name="com.searchviews.MainActivity"  
  18.             android:label="@string/app_name" >  
  19.       <intent-filter>  
  20.         <action android:name="android.intent.action.MAIN" />  
  21.    
  22.         <category android:name="android.intent.category.LAUNCHER" />  
  23.       </intent-filter>  
  24.       <meta-data android:name="android.app.default_searchable"  
  25.    
  26.               android:value=".SearchResultsActivity"/>  
  27.     </activity>  
  28.    
  29.     <activity  
  30.             android:name="com.searchviews.SearchResultsActivity"  
  31.             android:label="Search Activity">  
  32.       <intent-filter>  
  33.         <action android:name="android.intent.action.SEARCH" />  
  34.       </intent-filter>  
  35.       <meta-data  
  36.               android:name="android.app.searchable"  
  37.               android:resource="@xml/searchable" />  
  38.     </activity>  
  39.        
  40.   </application>  
  41.    
  42. </manifest> 
Note that if do not make your main activity (MainActivity) and the search activity (SearchResultsActivity) searchable, your code will not work.
 
The output snapshots:
 
im1.png
 
The red mark in the preceding figure shows the search icon. Clicking on it gives:
 
im2new.jpg
 
Enter the word:
 
im3new.jpg
 
Search Result:
 
im4new.jpg
 
Thank you... Enjoy coding :)


Similar Articles