我有Activity扩展AppCompatActivity。我想在更改屏幕方向后设置searchview查询。我得到了NPE错误
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.SearchView.setQuery(java.lang.CharSequence, boolean)' on a null object reference
如果我在Fragment中使用setQuery,它可以正常工作。在活动中它不起作用。 如何从活动中更改searchview查询?
MyActivity.java
@Override public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.bankmvp_menu, menu);
searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
searchManager = (SearchManager) this.getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(this.getComponentName()));
getObservableSearchViewText();
return true;
}
@Override public void setQueryToSearch(String querystring) {
searchView.setQuery(querystring, true); //NPE error
}
bankmvp_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MyActivity">
<item
android:id="@+id/action_setmonth"
android:orderInCategory="100"
android:title="@string/action_setmonth"
app:showAsAction="never" />
<item
android:id="@+id/action_setaccount"
android:orderInCategory="100"
android:title="@string/action_setaccount"
app:showAsAction="never" />
<item
android:id="@+id/action_nosaveddoc"
android:orderInCategory="100"
android:title="@string/action_nosaveddoc"
app:showAsAction="never" />
<item
android:id="@+id/action_search"
android:orderInCategory="100"
android:title="@string/action_search"
android:icon="@android:drawable/ic_menu_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always|collapseActionView"
/>
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
app:showAsAction="never" />
答案 0 :(得分:0)
将查询字符串从Presenter设置为Searchview
更改menu.xml
android:id="@+id/action_search"
android:orderInCategory="100"
android:title="@string/action_search"
android:icon="@android:drawable/ic_menu_search"
app:actionViewClass="android.support.v7.widget.SearchView"
android:iconifiedByDefault="true" //important
app:showAsAction="always" //important
更改活动,从Presenter设置仅字符串。
@Override public void setQueryToSearch(String querystringx) {
if( querystringx.equals("")){
}else {
querystring = querystringx;
}
}
在onResume of activity
中更改活动setQueryif( querystring.equals("")){
}else {
searchView.setIconified(false);
searchView.setQuery(querystring, false);
menuItem.setVisible(true);
}
更改方向后的屏幕