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. <TextView
  13. android:layout_width="wrap_content"
  14. android:layout_height="wrap_content"
  15. android:text="Hello World!"/>
  16. </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. <TextView
  13. android:layout_width="wrap_content"
  14. android:layout_height="wrap_content"
  15. android:textAppearance="?android:attr/textAppearanceLarge"
  16. android:text="Large Text"
  17. android:id="@+id/textView"
  18. android:layout_alignParentTop="true"
  19. android:layout_alignParentLeft="true"
  20. android:layout_alignParentStart="true"/>
  21. </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. import android.app.SearchManager;
  3. import android.content.ComponentName;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.os.Bundle;
  7. import android.support.v4.view.MenuItemCompat;
  8. import android.support.v7.app.AppCompatActivity;
  9. import android.support.v7.widget.SearchView;
  10. import android.view.Menu;
  11. import android.view.MenuItem;
  12. import android.widget.Toast;
  13. public class MainActivity extends AppCompatActivity
  14. implements SearchView.OnQueryTextListener {
  15. @Override
  16. protected void onCreate(Bundle savedInstanceState) {
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.activity_main);
  19. }
  20. @Override
  21. public boolean onCreateOptionsMenu(Menu menu) {
  22. getMenuInflater().inflate(R.menu.menu_search, menu);
  23. MenuItem searchItem = menu.findItem(R.id.search);
  24. SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
  25. searchView.setOnQueryTextListener(this);
  26. SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
  27. searchView.setSearchableInfo(searchManager.getSearchableInfo(
  28. new ComponentName(this, SearchableActivity.class)));
  29. searchView.setIconifiedByDefault(false);
  30. return true;
  31. }
  32. @Override
  33. protected void onNewIntent(Intent intent) {
  34. super.onNewIntent(intent);
  35. if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
  36. String query = intent.getStringExtra(SearchManager.QUERY);
  37. Toast.makeText(this, "Searching by: "+ query, Toast.LENGTH_SHORT).show();
  38. } else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
  39. String uri = intent.getDataString();
  40. Toast.makeText(this, "Suggestion: "+ uri, Toast.LENGTH_SHORT).show();
  41. }
  42. }
  43. @Override
  44. public boolean onQueryTextSubmit(String query) {
  45. // User pressed the search button
  46. return false;
  47. }
  48. @Override
  49. public boolean onQueryTextChange(String newText) {
  50. // User changed the text
  51. return false;
  52. }
  53. }
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. import android.app.SearchManager;
  3. import android.content.ContentProvider;
  4. import android.content.ContentValues;
  5. import android.content.UriMatcher;
  6. import android.database.Cursor;
  7. import android.database.MatrixCursor;
  8. import android.net.Uri;
  9. import android.provider.BaseColumns;
  10. import android.util.Log;
  11. import org.json.JSONArray;
  12. import java.util.ArrayList;
  13. import java.util.List;
  14. import okhttp3.OkHttpClient;
  15. import okhttp3.Request;
  16. import okhttp3.Response;
  17. public class CitySuggestionProvider extends ContentProvider {
  18. private static final String AUTHORITY = "ngvl.android.demosearch.citysuggestion";
  19. private static final int TYPE_ALL_SUGGESTIONS = 1;
  20. private static final int TYPE_SINGLE_SUGGESTION = 2;
  21. private UriMatcher mUriMatcher;
  22. private List<String> cities;
  23. @Override
  24. public boolean onCreate() {
  25. mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
  26. mUriMatcher.addURI(AUTHORITY, "/#", TYPE_SINGLE_SUGGESTION);
  27. mUriMatcher.addURI(AUTHORITY, "search_suggest_query/*", TYPE_ALL_SUGGESTIONS);
  28. return false;
  29. }
  30. @Override
  31. public Cursor query(Uri uri, String[] projection, String selection,
  32. String[] selectionArgs, String sortOrder) {
  33. if (cities == null || cities.isEmpty()){
  34. Log.d("NGVL", "WEB");
  35. OkHttpClient client = new OkHttpClient();
  36. Request request = new Request.Builder()
  37. .url("https://dl.dropboxusercontent.com/u/6802536/cidades.json")
  38. .build();
  39. try {
  40. Response response = client.newCall(request).execute();
  41. String jsonString = response.body().string();
  42. JSONArray jsonArray = new JSONArray(jsonString);
  43. cities = new ArrayList<>();
  44. int lenght = jsonArray.length();
  45. for (int i = 0; i < lenght; i++) {
  46. String city = jsonArray.getString(i);
  47. cities.add(city);
  48. }
  49. } catch (Exception e) {
  50. e.printStackTrace();
  51. }
  52. } else {
  53. Log.d("NGVL", "Cache!");
  54. }
  55. MatrixCursor cursor = new MatrixCursor(
  56. new String[] {
  57. BaseColumns._ID,
  58. SearchManager.SUGGEST_COLUMN_TEXT_1,
  59. SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID
  60. }
  61. );
  62. if (mUriMatcher.match(uri) == TYPE_ALL_SUGGESTIONS) {
  63. if (cities != null) {
  64. String query = uri.getLastPathSegment().toUpperCase();
  65. int limit = Integer.parseInt(uri.getQueryParameter(SearchManager.SUGGEST_PARAMETER_LIMIT));
  66. int lenght = cities.size();
  67. for (int i = 0; i < lenght && cursor.getCount() < limit; i++) {
  68. String city = cities.get(i);
  69. if (city.toUpperCase().contains(query)) {
  70. cursor.addRow(new Object[]{i, city, i});
  71. }
  72. }
  73. }
  74. } else if (mUriMatcher.match(uri) == TYPE_SINGLE_SUGGESTION) {
  75. int position = Integer.parseInt(uri.getLastPathSegment());
  76. String city = cities.get(position);
  77. cursor.addRow(new Object[]{position, city, position});
  78. }
  79. return cursor;
  80. }
  81. @Override
  82. public int delete(Uri uri, String selection, String[] selectionArgs) {
  83. throw new UnsupportedOperationException("Not yet implemented");
  84. }
  85. @Override
  86. public String getType(Uri uri) {
  87. throw new UnsupportedOperationException("Not yet implemented");
  88. }
  89. @Override
  90. public Uri insert(Uri uri, ContentValues values) {
  91. throw new UnsupportedOperationException("Not yet implemented");
  92. }
  93. @Override
  94. public int update(Uri uri, ContentValues values, String selection,
  95. String[] selectionArgs) {
  96. throw new UnsupportedOperationException("Not yet implemented");
  97. }
  98. }
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. import android.app.SearchManager;
  3. import android.content.AsyncQueryHandler;
  4. import android.content.Intent;
  5. import android.database.Cursor;
  6. import android.os.Bundle;
  7. import android.provider.BaseColumns;
  8. import android.support.v7.app.AppCompatActivity;
  9. import android.widget.TextView;
  10. import java.lang.ref.WeakReference;
  11. public class SearchableActivity extends AppCompatActivity {
  12. private MyHandler mHandler;
  13. private TextView txt;
  14. @Override
  15. protected void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. setContentView(R.layout.activity_searchable);
  18. txt = (TextView)findViewById(R.id.textView);
  19. Intent intent = getIntent();
  20. if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
  21. String query = intent.getStringExtra(SearchManager.QUERY);
  22. txt.setText("Searching by: "+ query);
  23. } else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
  24. mHandler = new MyHandler(this);
  25. mHandler.startQuery(0, null, intent.getData(), null, null, null, null);
  26. }
  27. }
  28. public void updateText(String text){
  29. txt.setText(text);
  30. }
  31. static class MyHandler extends AsyncQueryHandler {
  32. // avoid memory leak
  33. WeakReference<SearchableActivity> activity;
  34. public MyHandler(SearchableActivity searchableActivity) {
  35. super(searchableActivity.getContentResolver());
  36. activity = new WeakReference<>(searchableActivity);
  37. }
  38. @Override
  39. protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
  40. super.onQueryComplete(token, cookie, cursor);
  41. if (cursor == null || cursor.getCount() == 0) return;
  42. cursor.moveToFirst();
  43. long id = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
  44. String text = cursor.getString(cursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1));
  45. long dataId = cursor.getLong(cursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID));
  46. cursor.close();
  47. if (activity.get() != null) {
  48. activity.get().updateText("onQueryComplete: " + id + " / " + text + " / " + dataId);
  49. }
  50. }
  51. };
  52. }
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.