Android widget SearchView in onCreateOptionsMenu is null

If your class extends AppCompatActivity

public class SearchableActivity extends AppCompatActivity

Check if linked appropriate library for:

import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

Check if you have to properly sett SearchView in menu xml for onCreateOptionsMenu menu_main.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=".SearchableActivity">
<item

  android:id="@+id/menu_search_my"
        android:title="@string/menu_search"
        android:icon="@drawable/ic_menu_search"
        app:showAsAction="collapseActionView|ifRoom"
        app:actionViewClass="android.support.v7.widget.SearchView"

/></menu>

Check your SearchableActivity onCreateOptionsMenu

   @TargetApi(Build.VERSION_CODES.HONEYCOMB) @SuppressLint("NewApi") @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        if(Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.HONEYCOMB) {
 
            android.support.v7.widget.SearchView searchView = (android.support.v7.widget.SearchView)
                    MenuItemCompat.getActionView(menu.findItem(R.id.menu_search_my));
            SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
            if(null!=searchManager ) {
                searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
            }
            searchView.setIconifiedByDefault(false);
        }
        return true;
    }
This entry was posted in Android Studio, Bugs, warnings, errors and tagged , . Bookmark the permalink.


Comments are closed.



3,110 views