Implement Search Bar In Your Android App

Introduction

 
Android is one of the most popular operating systems for mobile. I will show you how to implement a search bar in your Android application using the Android studio.Android is the kernel-based operating system. It allows the user to modify the GUI components and source code.
 
Requirements

Steps should be followed

 
Carefully follow my steps to implement a search bar in your Android application using Android studio and I have included the source code below.
 
Step 1
 
Open Android Studio and start the new project.
 
search bar in Android
 
Step 2
 
Put the application name and company domain. If you wish to use c++ for coding the project, mark the Include c++ support then click next.
 
search in Android app
 
Step 3
 
Select the Android minimum SDK. After you chose the minimum SDK it will show an approximate percentage of people who use that sdk then click next.
 
search in Android app
 
Step 4
 
Choose the basic activity then click next.
 
search in Android app
 
Step 5
 
Put the activity name and layout name. Android studio basically takes the java class name as what you provide for the activity name and click finish.
 
search in Android app
 
Step 6
 
Go to activity_main.xml then click the text bottom. This XML file contains the designing code for the android app. Into the activity_main.xml copy and paste the below code.
 
Activity_main.xml code
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     xmlns:tools="http://schemas.android.com/tools"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     android:paddingBottom="@dimen/activity_vertical_margin"  
  8.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  9.     android:paddingRight="@dimen/activity_horizontal_margin"  
  10.     android:paddingTop="@dimen/activity_vertical_margin"  
  11.     tools:context="ngvl.android.demosearch.MainActivity">  
  12.   
  13.     <TextView  
  14.         android:layout_width="wrap_content"  
  15.         android:layout_height="wrap_content"  
  16.         android:text="Hello World!"/>  
  17. </RelativeLayout>  
search in Android app
 
Step 7
 
Create a new Activity_searchable.xml file (File ⇒ New ⇒Activity⇒Empty_activity).
 
Go to Activity_searchable.xml then click the text bottom. This xml file contains the designing code for the android app. Into the Activity_searchable.xml copy and paste the below code.
 
Activity_searchable.xml code
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     xmlns:tools="http://schemas.android.com/tools"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     android:paddingBottom="@dimen/activity_vertical_margin"  
  8.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  9.     android:paddingRight="@dimen/activity_horizontal_margin"  
  10.     android:paddingTop="@dimen/activity_vertical_margin"  
  11.     tools:context="ngvl.android.demosearch.SearchableActivity">  
  12.   
  13.     <TextView  
  14.         android:layout_width="wrap_content"  
  15.         android:layout_height="wrap_content"  
  16.         android:textAppearance="?android:attr/textAppearanceLarge"  
  17.         android:text="Large Text"  
  18.         android:id="@+id/textView"  
  19.         android:layout_alignParentTop="true"  
  20.         android:layout_alignParentLeft="true"  
  21.         android:layout_alignParentStart="true"/>  
  22. </RelativeLayout>  
search in Android app
 
Step 8
 
Into the MainActivity.java copy and paste the below code.java programming is the backend language for Android. Do not replace your package name otherwise, the app will not run.
 
MainActivity.java code
  1. package ngvl.android.demosearch;  
  2.   
  3. import android.app.SearchManager;  
  4. import android.content.ComponentName;  
  5. import android.content.Context;  
  6. import android.content.Intent;  
  7. import android.os.Bundle;  
  8. import android.support.v4.view.MenuItemCompat;  
  9. import android.support.v7.app.AppCompatActivity;  
  10. import android.support.v7.widget.SearchView;  
  11. import android.view.Menu;  
  12. import android.view.MenuItem;  
  13. import android.widget.Toast;  
  14.   
  15. public class MainActivity extends AppCompatActivity  
  16.         implements SearchView.OnQueryTextListener {  
  17.   
  18.     @Override  
  19.     protected void onCreate(Bundle savedInstanceState) {  
  20.         super.onCreate(savedInstanceState);  
  21.         setContentView(R.layout.activity_main);  
  22.     }  
  23.   
  24.     @Override  
  25.     public boolean onCreateOptionsMenu(Menu menu) {  
  26.         getMenuInflater().inflate(R.menu.menu_search, menu);  
  27.   
  28.         MenuItem searchItem = menu.findItem(R.id.search);  
  29.         SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);  
  30.         searchView.setOnQueryTextListener(this);  
  31.   
  32.         SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);  
  33.         searchView.setSearchableInfo(searchManager.getSearchableInfo(  
  34.                 new ComponentName(this, SearchableActivity.class)));  
  35.         searchView.setIconifiedByDefault(false);  
  36.   
  37.         return true;  
  38.     }  
  39.   
  40.     @Override  
  41.     protected void onNewIntent(Intent intent) {  
  42.         super.onNewIntent(intent);  
  43.         if (Intent.ACTION_SEARCH.equals(intent.getAction())) {  
  44.             String query = intent.getStringExtra(SearchManager.QUERY);  
  45.             Toast.makeText(this"Searching by: "+ query, Toast.LENGTH_SHORT).show();  
  46.   
  47.         } else if (Intent.ACTION_VIEW.equals(intent.getAction())) {  
  48.             String uri = intent.getDataString();  
  49.             Toast.makeText(this"Suggestion: "+ uri, Toast.LENGTH_SHORT).show();  
  50.         }  
  51.     }  
  52.   
  53.     @Override  
  54.     public boolean onQueryTextSubmit(String query) {  
  55.         // User pressed the search button  
  56.         return false;  
  57.     }  
  58.   
  59.     @Override  
  60.     public boolean onQueryTextChange(String newText) {  
  61.         // User changed the text  
  62.         return false;  
  63.     }  
  64. }  
Step 9
 
Create a new CitySuggesionProvider.java file (File ⇒ New ⇒Java class).
 
Into the CitySuggesionProvider.java copy and paste the below code. Java programming is the backend language for Android. Do not replace your package name otherwise, the app will not run.
 
CitySuggesionProvider.java code
  1. package ngvl.android.demosearch;  
  2.   
  3. import android.app.SearchManager;  
  4. import android.content.ContentProvider;  
  5. import android.content.ContentValues;  
  6. import android.content.UriMatcher;  
  7. import android.database.Cursor;  
  8. import android.database.MatrixCursor;  
  9. import android.net.Uri;  
  10. import android.provider.BaseColumns;  
  11. import android.util.Log;  
  12.   
  13. import org.json.JSONArray;  
  14.   
  15. import java.util.ArrayList;  
  16. import java.util.List;  
  17.   
  18. import okhttp3.OkHttpClient;  
  19. import okhttp3.Request;  
  20. import okhttp3.Response;  
  21.   
  22. public class CitySuggestionProvider extends ContentProvider {  
  23.   
  24.     private static final String AUTHORITY = "ngvl.android.demosearch.citysuggestion";  
  25.   
  26.     private static final int TYPE_ALL_SUGGESTIONS = 1;  
  27.     private static final int TYPE_SINGLE_SUGGESTION = 2;  
  28.   
  29.     private UriMatcher mUriMatcher;  
  30.     private List<String> cities;  
  31.   
  32.     @Override  
  33.     public boolean onCreate() {  
  34.         mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);  
  35.         mUriMatcher.addURI(AUTHORITY, "/#", TYPE_SINGLE_SUGGESTION);  
  36.         mUriMatcher.addURI(AUTHORITY, "search_suggest_query/*", TYPE_ALL_SUGGESTIONS);  
  37.         return false;  
  38.     }  
  39.   
  40.     @Override  
  41.     public Cursor query(Uri uri, String[] projection, String selection,  
  42.                         String[] selectionArgs, String sortOrder) {  
  43.         if (cities == null || cities.isEmpty()){  
  44.             Log.d("NGVL""WEB");  
  45.             OkHttpClient client = new OkHttpClient();  
  46.             Request request = new Request.Builder()  
  47.                     .url("https://dl.dropboxusercontent.com/u/6802536/cidades.json")  
  48.                     .build();  
  49.   
  50.             try {  
  51.                 Response response = client.newCall(request).execute();  
  52.                 String jsonString = response.body().string();  
  53.                 JSONArray jsonArray = new JSONArray(jsonString);  
  54.   
  55.                 cities = new ArrayList<>();  
  56.   
  57.                 int lenght = jsonArray.length();  
  58.                 for (int i = 0; i < lenght; i++) {  
  59.                     String city = jsonArray.getString(i);  
  60.                     cities.add(city);  
  61.                 }  
  62.   
  63.             } catch (Exception e) {  
  64.                 e.printStackTrace();  
  65.             }  
  66.         } else {  
  67.             Log.d("NGVL""Cache!");  
  68.         }  
  69.   
  70.         MatrixCursor cursor = new MatrixCursor(  
  71.                 new String[] {  
  72.                         BaseColumns._ID,  
  73.                         SearchManager.SUGGEST_COLUMN_TEXT_1,  
  74.                         SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID  
  75.                 }  
  76.         );  
  77.   
  78.         if (mUriMatcher.match(uri) == TYPE_ALL_SUGGESTIONS) {  
  79.             if (cities != null) {  
  80.                 String query = uri.getLastPathSegment().toUpperCase();  
  81.                 int limit = Integer.parseInt(uri.getQueryParameter(SearchManager.SUGGEST_PARAMETER_LIMIT));  
  82.   
  83.                 int lenght = cities.size();  
  84.                 for (int i = 0; i < lenght && cursor.getCount() < limit; i++) {  
  85.                     String city = cities.get(i);  
  86.                     if (city.toUpperCase().contains(query)) {  
  87.                         cursor.addRow(new Object[]{i, city, i});  
  88.                     }  
  89.                 }  
  90.             }  
  91.         } else if (mUriMatcher.match(uri) == TYPE_SINGLE_SUGGESTION) {  
  92.             int position = Integer.parseInt(uri.getLastPathSegment());  
  93.             String city = cities.get(position);  
  94.             cursor.addRow(new Object[]{position, city, position});  
  95.         }  
  96.         return cursor;  
  97.     }  
  98.   
  99.     @Override  
  100.     public int delete(Uri uri, String selection, String[] selectionArgs) {  
  101.         throw new UnsupportedOperationException("Not yet implemented");  
  102.     }  
  103.   
  104.     @Override  
  105.     public String getType(Uri uri) {  
  106.         throw new UnsupportedOperationException("Not yet implemented");  
  107.     }  
  108.   
  109.     @Override  
  110.     public Uri insert(Uri uri, ContentValues values) {  
  111.         throw new UnsupportedOperationException("Not yet implemented");  
  112.     }  
  113.   
  114.     @Override  
  115.     public int update(Uri uri, ContentValues values, String selection,  
  116.                       String[] selectionArgs) {  
  117.         throw new UnsupportedOperationException("Not yet implemented");  
  118.     }  
  119. }  
Step 10
 
Create a new SearchableActivity.java file (File ⇒ New ⇒Java class).
 
Into the SearchableActivity.java copy and paste the below code.java programming is the backend language for Android. Do not replace your package name otherwise, the app will not run.
 
SearchableActivity.java code
  1. package ngvl.android.demosearch;  
  2.   
  3. import android.app.SearchManager;  
  4. import android.content.AsyncQueryHandler;  
  5. import android.content.Intent;  
  6. import android.database.Cursor;  
  7. import android.os.Bundle;  
  8. import android.provider.BaseColumns;  
  9. import android.support.v7.app.AppCompatActivity;  
  10. import android.widget.TextView;  
  11.   
  12. import java.lang.ref.WeakReference;  
  13.   
  14. public class SearchableActivity extends AppCompatActivity {  
  15.   
  16.     private MyHandler mHandler;  
  17.   
  18.     private TextView txt;  
  19.   
  20.     @Override  
  21.     protected void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         setContentView(R.layout.activity_searchable);  
  24.         txt = (TextView)findViewById(R.id.textView);  
  25.   
  26.         Intent intent = getIntent();  
  27.         if (Intent.ACTION_SEARCH.equals(intent.getAction())) {  
  28.             String query = intent.getStringExtra(SearchManager.QUERY);  
  29.             txt.setText("Searching by: "+ query);  
  30.   
  31.         } else if (Intent.ACTION_VIEW.equals(intent.getAction())) {  
  32.             mHandler = new MyHandler(this);  
  33.             mHandler.startQuery(0, null, intent.getData(), nullnullnullnull);  
  34.         }  
  35.     }  
  36.   
  37.     public void updateText(String text){  
  38.         txt.setText(text);  
  39.     }  
  40.   
  41.     static class MyHandler extends AsyncQueryHandler {  
  42.         // avoid memory leak  
  43.         WeakReference<SearchableActivity> activity;  
  44.   
  45.         public MyHandler(SearchableActivity searchableActivity) {  
  46.             super(searchableActivity.getContentResolver());  
  47.             activity = new WeakReference<>(searchableActivity);  
  48.         }  
  49.   
  50.         @Override  
  51.         protected void onQueryComplete(int token, Object cookie, Cursor cursor) {  
  52.             super.onQueryComplete(token, cookie, cursor);  
  53.             if (cursor == null || cursor.getCount() == 0) return;  
  54.   
  55.             cursor.moveToFirst();  
  56.   
  57.             long id = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));  
  58.             String text = cursor.getString(cursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1));  
  59.             long dataId =  cursor.getLong(cursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID));  
  60.   
  61.             cursor.close();  
  62.   
  63.             if (activity.get() != null) {  
  64.                 activity.get().updateText("onQueryComplete: " + id + " / " + text + " / " + dataId);  
  65.             }  
  66.         }  
  67.     };  
  68. }  
Step 11
 
Create a new dimens.xml file into the values folder (File ⇒ New ⇒Activity⇒Empty_activity).
 
Go to dimens.xml then click the text bottom. This XML file contains the designing code for the android app. Into the dimens.xml copy and paste the below code.
 
dimens.xml code
  1. <resources>  
  2.     <!-- Default screen margins, per the Android Design guidelines. -->  
  3.     <dimen name="activity_horizontal_margin">16dp</dimen>  
  4.     <dimen name="activity_vertical_margin">16dp</dimen>  
  5. </resources>  
Step 12
 
Create an XML folder into the values folder.
 
Create a new searchable.xml file into the values folder (File ⇒ New ⇒Activity⇒Empty_activity).
 
Go to searchable.xml then click the text bottom. This XML file contains the designing code for the Android app. Go into the searchable.xml copy and paste the below code. Below the list of strings contains ringtones name list.
 
searchable.xml code
  1. <searchable xmlns:android="http://schemas.android.com/apk/res/android"  
  2.             android:hint="@string/hint_search"  
  3.             android:label="@string/app_name"  
  4.             android:voiceSearchMode="showVoiceSearchButton|launchRecognizer"  
  5.             android:searchSuggestAuthority="ngvl.android.demosearch.citysuggestion"  
  6.             android:searchSuggestIntentAction="android.intent.action.VIEW"  
  7.             android:searchSuggestIntentData="content://ngvl.android.demosearch.citysuggestion"/>  
Step 13
 
Create new strings.xml file into the values folder (File ⇒ New ⇒Activity⇒Empty_activity).
 
Go to strings.xml then click the text bottom. This XML file contains the designing code for the Android app. Go into the strings.xml copy and paste the below code. The below list of strings contains the ringtones name list.
 
strings.xml code
  1. <resources>  
  2.     <string name="app_name">DemoSearch</string>  
  3.     <string name="hint_search">Searching for…</string>  
  4.     <string name="search_description">City, Cities</string>  
  5. </resources>  
Step 14
 
Click the make project option and run.
 
search in Android app
 
Deliverables
 
Here search bar in your android application is successfully created and executed.
 
search in Android app
 
search in Android app
 
search in Android app
 
Don’t forget to like and follow me. If you have any doubts just comment below.


Similar Articles