3

I have added android X in xml

 public boolean onCreateOptionsMenu(final Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.notebook_menu, menu);
    MenuItem searchMenuItem = menu.findItem(R.id.notebook_search);      
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    searchView = (SearchView) searchMenuItem.getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setIconifiedByDefault(false);    
    }

From menu

  <menu xmlns:android="http://schemas.android.com/apk/res/android" >
        <item
        android:id="@+id/notebook_search"
        app:actionViewClass="androidx.appcompat.widget.SearchView"
        android:icon="@drawable/tab_notebook_search"
        app:showAsAction="always|collapseActionView"
        android:title="@string/search"/>
        </menu>

Error

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SearchView.setSearchableInfo(android.app.SearchableInfo)' on a null object reference

Bee
  • 142
  • 17
  • 1
    Please provide a [mcve]. Be sure to show the full error message. Check out https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this for some tips. – Code-Apprentice Oct 16 '19 at 15:37
  • menu.xml file android:actionViewClass="androidx.appcompat.widget.SearchView" Java class searchView = (SearchView) searchMenuItem.getActionView();//getting null here Error java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SearchView.setSearchableInfo(android.app.SearchableInfo)' on a null object reference – Kalpana Sahu Oct 16 '19 at 15:46
  • Did you read the links I provided? – Code-Apprentice Oct 16 '19 at 16:07

1 Answers1

2

Use app:actionViewClass instead of android:actionViewClass in your menu layout. That's the problem. Change like below:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/notebook_search"
        app:actionViewClass="androidx.appcompat.widget.SearchView"
        android:icon="@drawable/tab_notebook_search"
        app:showAsAction="always|collapseActionView"
        android:title="@string/search"/>
</menu>

Beside this probably your refactor not correctly done. Please Try Refactor > Migrate to AndroidX and press DoRefactor

Md. Asaduzzaman
  • 14,963
  • 2
  • 34
  • 46