TheUnreal TheUnreal - 4 months ago 44
Android Question

Menu SearchView not recognized

It's not a duplicate, AS WRITTEN IN MY QUESTION I already tried thoes solutions and got the same error.

I have the following code:

MainActivity

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
search(query);
return true;
}

@Override
public boolean onQueryTextChange(String query) {
//filterSearchFor(query);
return true;
}
});
return true;
}


menu/menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">

<android.support.v7.widget.SearchView
android:id="@+id/search"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</menu>


I got this error:

FATAL EXCEPTION: main
Process: com.pgoiv.pokemongoiv, PID: 5336
java.lang.NullPointerException: Attempt to invoke interface method 'android.view.View android.view.MenuItem.getActionView()' on a null object reference
at com.pgoiv.pokemongoiv.MainActivity.onCreateOptionsMenu(MainActivity.java:192)
at


Tried few solutions of people who had the same error.. couldn't figure out what's wrong..

Seem likt
menu.findItem(R.id.search)
can't find my searchview although it's there as you can see in my xml file..

Answer

You can't insert SearchView into menu like this. Try this in your menu.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item
        android:id="@+id/action_search"
        android:orderInCategory="100"
        android:title="Search"
        android:icon="@drawable/ic_menu_search"
        app:showAsAction="ifRoom|collapseActionView"
        app:actionViewClass="android.support.v7.widget.SearchView"/>

</menu>