NullPointerException-: attempt to call the interface method "android.view.View android.view.MenuItem.getActionView ()" in a reference to a null object

I am trying to add a search string to an Actionbar and have detected a Nullpointer exception in getActionVeiw (). Prisoners help me solve this problem, I provided the necessary information.

My MainActivity extends AppCompatActivity and returns an error in this line of code

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

searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

for the above searchview I am importing

import android.support.v7.widget.SearchView;

Menu file main.xml

  <item
        android:id="@+id/action_search"
        android:orderInCategory="100"
        android:title="@string/action_search"
        app:showAsAction="always"
        app:actionViewClass="android.support.v7.widget.SearchView" />

Gradle File -

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.android.support:support-v4:+'
    compile 'com.android.support:appcompat-v7:+'
    compile 'com.google.android.gms:play-services-appindexing:8.1.0'
}
+4
source share
2 answers

Download the full version of COde.

you need to initialize

getMenuInflater().inflate(R.menu.menu_main, menu); 

or should you delcare

MenuInflater inflater = getMenuInflater();
inflater.inflate()

then use this code in onCreateOptionsMenu ()

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

    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

For example -:

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.

        // Associate searchable configuration with the SearchView
        getMenuInflater().inflate(R.menu.menu_main, menu);
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

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

        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

        this.menu = menu;  // this will copy menu values to upper defined menu so that we can change icon later akash

        return true;
    }

Try it.

+6

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

. fooobar.com/questions/332169/...

+1

Source: https://habr.com/ru/post/1620862/


All Articles