我正在CustomAdapter上执行SearchView,它将搜索Gate Name.我尝试运行应用程序后,它突然崩溃,并给我如上所述的错误.我不知道哪个部分甚至做错了导致每次我尝试运行我的应用程序时出现此问题.
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"/>
这是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
它还表明错误也来自这行代码:
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
我希望有人能够为我提供解决问题的解决方案.
解决方法:
将您的android:actionViewClass更改为app:actionViewClass,因为您正在使用来自支持lib的SearchView
<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">