Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException-: Attempt to invoke interface method "android.view.View android.view.MenuItem.getActionView()' on a null object reference

I am trying to add search bar on Actionbar and found Nullpointer exception on getActionVeiw(). Pleaes help me to short out this problem I have provided the required detail.

My MainActivity extends AppCompatActivity and return error on this line of code

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

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

for above searchview I am importing

import android.support.v7.widget.SearchView;

Menu main.xml file

  <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'
}
like image 749
Akash Avatar asked Dec 19 '15 10:12

Akash


2 Answers

Please Upload the Complete COde.

you have to initialize

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

or you have to 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 this.

like image 168
Akash kumar Avatar answered Nov 11 '22 18:11

Akash kumar


Try Below

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

See here https://stackoverflow.com/a/26565033/5202007

like image 34
Mohammad Tauqir Avatar answered Nov 11 '22 18:11

Mohammad Tauqir