If at first you don't succeed; call it version 1.0
Leassons Learned: Android SearchView
While working on a project that requires some android skills, I ran into some problems while coding a Search View. A search views is basically that nice looking search prompt that appears in an app’s action bar… like this:
There is an excellent guide by the folks at google on how to implement searchviews that’s right here:
But, being a newbie android devloper, two things bit me in the heinie (this article assumes you went through the above link, or have an already working knowledge of android searchviews):
1. What exactly do you have to place into the menu xml to represent the searchview widget in the action bar? For future reference, you’d need something like:
<item android:id="@+id/menu_search" android:actionViewClass="android.widget.SearchView" android:icon="@android:drawable/ic_menu_search" android:showAsAction="always" android:title="@string/search"/>
Your app will simply not display the search widget without something like the above.
2. In my particular project, my “searchable activity” was not in the same file/class as the main activity. This lead to one of two problems, either the app starts throwing null pointer exceptions when arriving to the searchView.setSearchableInfo part, or trying to run a search doesn’t do anything.
From the “configuring search widget” section of the android dev documentation, you see:
// Get the SearchView and set the searchable configuration SearchManager searchManager = (SearchManager)
getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView(); // Assumes current activity is the searchable activity searchView.setSearchableInfo(searchManager.getSearchableInfo(
getComponentName())); searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
Note the comment in bold that explicitly states that the sample assumes the current activity is the searchable activity. What if it’s not? Some researching and digging around in the android API yielded:
searchView.getSearchableInfo( new ComponentName(this, SearchableActivity.class) )
Also, another very useful post from the android devs when implementing searchviews, especially the intent handling code at the very bottom of the page is here:
Basic stuff but hoping it helps some other newbie a bit of hair tearing….