Question

I have a search view in my activity. When I am trying to attach an OnQueryTextListener, it gives me a NullPointerException. Its Java code is as follows

    @Override
public  boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.allpurpose, menu);
    MenuItem        searchItem  = menu.findItem(R.id.apmenu_search);
    SearchView      searchView  = (SearchView) MenuItemCompat.getActionView(searchItem);
    SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
        public boolean onQueryTextChange(String newText) {return true;}
        public boolean onQueryTextSubmit(String query) {return true;}
    };
   searchView.setOnQueryTextListener(queryTextListener);
   return   super.onCreateOptionsMenu(menu);
}

XML Code:

 <?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/apmenu_search"
    android:icon="@android:drawable/ic_menu_search"
    android:title="@string/srch"
    android:showAsAction="ifRoom"
    android:actionViewClass="android.support.v7.widget.SearchView" />
</menu>
Was it helpful?

Solution

All "Compat" items are used to provide backward compatibility. So in this case MenuItemCompat supports action bar items for versions above 7 (instead of the normal 11). In the java code, if there is MenuItemCompat, then in the xml too there must be a "Compat" item. Now, the "app" namespace supports these "Compat" items. So change the xml like this:

<?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/apmenu_search"
            android:icon="@android:drawable/ic_menu_search"
            android:title="@string/srch"
            app:showAsAction="ifRoom"
            app:actionViewClass="android.support.v7.widget.SearchView" />
</menu>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top