mkandro mkandro - 3 months ago 19
Android Question

NullPointerException in Android code

The error is:

java.lang.NullPointerException.onCreateOptionsMenu(AddMyMarketsActivity.java:44)


My code is:

41 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
42 SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
43 SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
44 searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
Log.i("searchView", "set searchable configuration for searchView ");


What could be the problem with my code?

Answer

If you're using androids support libary to display your action bar, be sure you use the right actionViewClass in your SearchView declaration.

Should be app:actionViewClass="android.support.v7.widget.SearchView".

After that you can use as replacement for your code trying to get the ActionView:

MenuItem searchItem = menu.findItem(R.id.search_view);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);

Be sure to call getMenuInfalter().inflate(...) before calling this.

More information: http://developer.android.com/guide/topics/ui/actionbar.html#ActionView