Item added to ActionBar programmatically



i'm tring to add the Search item to my ActionBar. I wrote this code.



@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.add(0, 1, Menu.NONE, "Search").setIcon(R.drawable.ic_action_search).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

searchView = (SearchView)MenuItemCompat.getActionView(menu.findItem(1));

searchView.setOnQueryTextListener(new OnQueryTextListener() {

@Override
public boolean onQueryTextChange(String arg0) {
// TODO Auto-generated method stub
return false;
}

@Override
public boolean onQueryTextSubmit(String arg0) {
// TODO Auto-generated method stub
return false;
}

});

}


But when i run the app crash with this error



11-23 14:17:45.294: E/AndroidRuntime(28399): java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.SearchView.setOnQueryTextListener(android.support.v7.widget.SearchView$OnQueryTextListener)' on a null object reference


Okay, the logcat says that searchView is null but why? His id is 1 and i find the item with findItem method passing the id of the item that is 1. How can i solve?


P.S. I'm in a Fragment.


No comments:

Post a Comment