Search Android Toolbar
I am trying to create a searchview in my android app toolbar, but I am getting a null pointer exception on the third line of the onCreateoptionsMenu method. Any help would be appreciated, thanks in advance.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
SearchManager searchManager =(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =(SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
return true;
}
Here is my menu.xml -
<item
android:icon="@drawable/ic_search"
android:id="@+id/action_search"
android:orderInCategory="200"
android:title="Search"
app:showAsAction="ifRoom" />
source to share
You missed an attribute app:actionViewClass="android.support.v7.widget.SearchView"
. And you need to importandroid.support.v7.widget.SearchView;
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_search"
android:icon="@drawable/search"
android:title="@string/Search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always|collapseActionView" />
</menu>
source to share
You forgot to add actionViewClass
to menu.xml
Add these lines to you menu.xml
...
app:showAsAction="always|collapseActionView"
android:actionViewClass="android.support.v7.widget.SearchView" />
While in your Java code, find SearchView
using -
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
Reference - MenuItemCompat
source to share
Try using this
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Inflate menu to add items to action bar if it is present.
inflater.inflate(R.menu.menu_main, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
return true;
}
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:appcompat="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/tools">
<item
android:id="@+id/action_settings"
android:title="@string/action_settings"
android:orderInCategory="100"
app:showAsAction="never"/>
<item
android:id="@+id/menu_search"
android:title="@string/menu_search"
appcompat:actionViewClass="android.support.v7.widget.SearchView"
appcompat:showAsAction="always"/>
source to share