I am doing SearchView on CustomAdapter where it will search Gate Name. After i try run the app, it suddenly crash and give me the error as stated above. I do not know which part did i even do wrong that cause this issue to appear everytime i try to run my app.
MainActivity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
MenuItem searchItem = menu.findItem(R.id.item_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
List<Gate> gateSearchList = new ArrayList<Gate>();
for (Gate gate : gateList) {
if (gate.getGateName().toLowerCase().contains(newText.toLowerCase())) {
gateSearchList.add(gate);
}
}
adapter = new GateAdapter(MainActivity.this, gateSearchList);
lv.setAdapter(adapter);
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_logout) {
logout();
}
return super.onOptionsItemSelected(item);
}
main_menu.xml
<item
android:id="@+id/item_search"
android:icon="@drawable/ic_action_search"
android:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom|collapseActionView"
android:title="Search">
</item>
<item android:id="@+id/action_logout"
android:title="Log Out"
app:showAsAction="never"/>
This is the error message in logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.SearchView.setOnQueryTextListener(android.support.v7.widget.SearchView$OnQueryTextListener)' on a null object reference
It also indicate that the error also came from this line of code:
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
I hope someone can be able to provide me the solution to solve my issue.
Change your android:actionViewClass
to app:actionViewClass
, because you are using SearchView
from support lib
<item
android:id="@+id/item_search"
android:icon="@drawable/ic_action_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom|collapseActionView"
android:title="Search">
Posting this here for others who might face the similar issue.
Following up Jasmin John's Point I Have solved the issue with pro-guard rule by adding
-keep class android.support.v7.widget.SearchView { *; }
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