我几天来一直在使用android中的搜索功能。无法查明错误。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exclude_list);
.......
SearchView searchView = (SearchView)findViewById(R.id.options_menu_main_search);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
if(null!=searchManager ) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
}
handleIntent(getIntent());
}
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
Log.i("q",query);
}
}
searchable.xml
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="@string/search_hint"
android:includeInGlobalSearch="false"
android:label="@string/app_name"
android:searchSettingsDescription="@string/search_hint" />
menu.xml文件
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Search, should appear as action button -->
<item
android:id="@+id/options_menu_main_search"
android:actionViewClass="android.support.v7.widget.SearchView"
android:icon="@drawable/ic_action_search"
android:showAsAction="always"
android:title="Search"/>
</menu>
清单
<activity
android:name="com.xyz.Exclude_list"
android:label="@string/title_activity_exclude_list"
android:screenOrientation="portrait"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
<action android:name="android.intent.action.VIEW" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable"
android:value=".app.Search"
/>
</activity>
错误
Caused by: java.lang.NullPointerException
at com.xyz.Exclude_list.onCreate(Exclude_list.java:64)
第64行:searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
如果我删除
SearchView searchView = (SearchView)findViewById(R.id.options_menu_main_search);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
if(null!=searchManager ) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
}
搜索工作正常但我在搜索中输入时无法获取/记录任何查询。
答案 0 :(得分:1)
您正尝试初始化MenuItem
内部onCreate
方法。您应该在onCreateOptionsMenu
方法中将其初始化为:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.options_menu_main_search).getActionView();
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
if(null!=searchManager ) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
}
}
请参阅文档中的Using Search Widget主题,特别是配置搜索小部件部分。另外,因为您没有使用AppCompat
库,所以您应该使用此类(如the docs中所声明的那样):
android:actionViewClass="android.widget.SearchView"