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'
}
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.
Try Below
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
See here https://stackoverflow.com/a/26565033/5202007
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With